conversion of decimal to binary output - ios

I am facing problem with the objective c code to convert decimal to binary. When I enter small values it shows me the output.
For e.g. 12 -> 1010
But when I enters large numbers, it shows me the output as "10..." (includes dots in the output)
Please help me.
My program is as follows:
NSUInteger x = [newDec integerValue];
//int y[30];
int i=0;
int m =1;
while (x != 0) {
int mod = x % 2;
x /= 2;
i = i + mod * m;
m = m * 10;
string = [NSString stringWithFormat:#"%d", i];
}

There are two problems with your code.
1) Your label size is perhaps not able to accommodate your string. So check the length of it.
2) Your code will not support the conversion if value of x is large. The reason is that int has limited capacity. Check this question regarding memory size of in-built variable. So, consider making your string mutable and add 0s or 1s in it. I am attaching my snippet of code.
NSMutableString *string = [[NSMutableString alloc] init];
while (x != 0) {
int mod = x % 2;
x /= 2;
[string insertString:[NSString stringWithFormat:#"%d", mod] atIndex:0];
}
NSLog(#"String = %#", string);

Related

How to create random numbers for multiple images to show randomly in Grid without repetition in iOS?

I create GridView in SpriteKit.my requirement is to shuffle images randomly in Grid View.
Here is my code to show images randomly without repetition.but this code is working for only two images.for multiple images this code is not working.
int RandomRowMainImage = arc4random_uniform(3);
int RandomColumnMainImage = arc4random_uniform(3);
//
int RandomRowOtherImage = arc4random_uniform(3);
int RandomColumnOtherImage = arc4random_uniform(3);
NSLog(#"RandomRowMain:%d \n Random Column :%d \n RandomRow1:%d \n randomColumn1 :%d",RandomRowMainImage,RandomColumnMainImage,RandomRowOtherImage,RandomColumnOtherImage);
//
BOOL checkStatus = [self checkRandomNumberColumRowLogic:RandomRowMainImage withMainRow:RandomColumnMainImage withOtherColumn:RandomColumnOtherImage withOtherRow:RandomRowOtherImage];
if (checkStatus) {
imgIcons.position = [self GridPosition:MainRowCount Column:MainColumnCount];
imgOtherImage.position = [self GridPosition:otherRowCount Column:otherColumnCount];
}
than Code for Position of Images
//Grid Position
-(CGPoint)GridPosition:(int)Row Column:(int)Column
{
CGFloat offset = SizeOfGrid / 2.0 + 0.5;
CGFloat x = Column * SizeOfGrid - (SizeOfGrid*TotalCol)/2.0 + offset;
CGFloat y = (TotalRows-Row-1) * SizeOfGrid -(SizeOfGrid*TotalRows)/2.0 + offset;
return CGPointMake(x, y);}
//Code to check prevent duplication of repeat random number for Two Images.
- (BOOL)checkRandomNumberColumRowLogic:(int)MainColumn withMainRow:(int)mainRow withOtherColumn:(int)otherColumn withOtherRow:(int)otherRow {
BOOL CompareRow = false;
BOOL CompareColumn = false;
if (mainRow == otherRow) {
int otherRow = 0;
for (int i = 0; i < TotalCol; i++ ) {
otherRow = [self checkRandomNumberCompare:otherRow];
if (MainColumn == otherRow) {
CompareRow = true;
break;
}
}
MainColumnCount = mainRow;
otherColumnCount = otherRow;
}
else {
CompareRow = true;
MainRowCount = mainRow;
otherRowCount = otherRow;
}
if (MainColumn == otherColumn) {
int otherCol = 0;
for (int i = 0; i < TotalCol; i++ ) {
otherCol = [self checkRandomNumberCompare:otherColumn];
if (MainColumn == otherCol) {
CompareColumn = true;
break;
}
}
MainColumnCount = MainColumn;
otherColumnCount = otherCol;
}
else {
CompareColumn = true;
MainColumnCount = MainColumn;
otherColumnCount = otherColumn;
}
if(CompareRow == CompareColumn) {
return true;
} else {
return false;
}
}
-(int)checkRandomNumberCompare:(int)compareRow {
int compareDiff = arc4random_uniform(TotalRows);
return compareDiff;
}
can you please help to display multiple images without repeat? like one time one image in Node
Sorry, but the logic of your checkRandomNumberColumRowLogic: method baffles me. Given two coordinates (x1, y1) and (x2, y2) then they represent the same point if and only if x1 == x2 and y1 == y2, and if this is not fall then they represent different points.
Here is the outline of a possible algorithm to solve your problem. First consider that given a rectangular grid of cells where the rows and columns are numbered starting from 0 then each cell can be assigned a unique number by multiplying its row index by the number of columns and adding in its column index. A diagram is worth a thousand words, given a 3 x 3 grid you get the numbering:
0 1 2
3 4 5
6 7 8
Note that given a cell number the row & column it represents can be calculated using integer division and remainder.
Doing the above reduces your problem to producing the numbers from 0 to rowCount x colCount - 1 in some random order.
There are a number of ways in which you can do this, here is one:
Set upperLimit to rowCount x colCount - 1
Generate a random number r between 0 and upperLimit
Check if cell r is occupied, if it is add 1 to r and repeat this step
Place next image into cell r
Subtract 1 from upperLimit and goto step 2 if the result is greater than 0 (of course "goto" here translates to a "while" in code)
They key to avoiding duplicates is step 3, and the algorithm guarantees that step 3 will always find an unoccupied cell – proving that is left as an exercise.
HTH
I'd agree with the answer above that your logic is overly complicated. If you give an index to each image as suggested, e.g. for a 3x4 grid:
0 1 2
3 4 5
6 7 8
9 10 11
You could then randomise the grid and exchange those images. The following code would achieve this:
-(void)createRandomGridArrays
{
NSInteger columnLength = 3;
NSInteger rowLength = 4;
// Create an array of NSNumbers up to the max then randomise
NSMutableArray *indexes = [NSMutableArray new];
for (NSInteger i=0; i<columnLength*rowLength; i++) {
[indexes addObject:#(i)];
}
NSArray *randomIndexes = [self shuffleArray:indexes];
NSLog(#"%# -> %#", indexes, randomIndexes);
// (0,1,2,3,4,5,6,7,8,9,10,11) -> (1,0,6,10,4,2,7,11,9,5,8,3)
// Convert indexes back to row/columns
for (NSNumber *randomIndex in randomIndexes) {
NSInteger index = [randomIndex integerValue];
NSInteger row = index % rowLength;
NSInteger column = index % columnLength;
NSLog(#"%ld row:%ld, column:%ld", index, row, column);
}
}
-(NSArray*)shuffleArray:(NSArray*)array
{
NSMutableArray *shuffledArray = [array mutableCopy];
for (NSInteger i=shuffledArray.count-1; i>0; i--) {
[shuffledArray exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}
return shuffledArray;
}
If you had an NSMutableArray of images you would then just exchange the image at index with the image at [randomIndexes[index] integerValue].

Generate any random NSInteger with exactly 18 digits

I tried this:
NSInteger numberFinal = 100000000000000000 + ((float)arc4random() / UINT32_MAX) * (999999999999999999 - 100000000000000000);
but it returns zero... I don't want to specify the range, but just want any number with 18 digits...
For your requirement, as #duDE mentioned you can't use a NSInteger to save 18 digit number, but there is a solution using NSString.
NSString *eighteenDigitNumberString = [[NSNumber numberWithInt:1 + arc4random_uniform(9)] stringValue];
for (int i = 0; i < 17; i++) {
eighteenDigitNumberString = [eighteenDigitNumberString stringByAppendingString:[[NSNumber numberWithInt:arc4random_uniform(10)] stringValue]];
}
NSLog(#"eighteenDigitNumberString : %#", eighteenDigitNumberString);
There we go, no need to explain everything is straightforward.
EDITED: if you really want a long long value you can do so:
long long eighteenDigitNumberLongLong = [eighteenDigitNumberString longLongValue];
EDITED: To avoid the leading 0 the initial string has been initiated with a non-zero number and the loop is running only 17 times.
As the maximum value of an NSInteger is NSIntegerMax, you cann't use NSInteger for your purpose:
enum {
NSNotFound = NSIntegerMax
};
Prior to OS X v10.5, NSNotFound was defined as 0x7fffffff.
This is 2147483647 (decimal).
If you need "any number" with 18 digits (as #A-Live assumes), you can take NSFloat for example.
A 18 digit integer will require a long long type.
Create two 9 digit random numbers, multiple one by 10^9 and add to the other.
const u_int32_t digits9 = 1000000000;
u_int32_t ms = arc4random_uniform(digits9);
u_int32_t ls = arc4random_uniform(digits9);
unsigned long long random18 = ((unsigned long long)ms * digits9) + ls;
NSLog(#"Example random18: %018llu", random18);
Output:
Example random18: 501895974656079554
If the number must have a leading non zero digit:
const u_int32_t digits81 = 100000000;
const u_int32_t digits89 = 900000000;
const u_int32_t digits9 = 1000000000;
u_int32_t ms = arc4random_uniform(digits89) + digits81;
u_int32_t ls = arc4random_uniform(digits9);
unsigned long long random18 = ((unsigned long long)ms * digits9) + ls;
If you need strictly 18 digits it would be better to use this code:
NSString *stringNumber = [NSString string];
for (int i = 0; i < 18; i++) {
if (i == 0) {
stringNumber = [stringNumber stringByAppendingString:[NSString stringWithFormat:#"%#", #(arc4random_uniform(9) + 1)]];
} else {
stringNumber = [stringNumber stringByAppendingString:[NSString stringWithFormat:#"%#", #(arc4random_uniform(10))]];
}
}
long long value = stringNumber.longLongValue;
You need the first condition because with the possibility of 0.1 you may receive 0 as the first digit, then your 18-digit integer would become 17-digit, with 0.01 possibility - 16-digit integer etc.
You're getting into unsigned long long territory...
#define ARC4RANDOM_MAX 0x100000000
float val = ((double)arc4random() / ARC4RANDOM_MAX);
unsigned long long numberToAdd = val * (900000000000000000-1);
unsigned long long numberFinal = 100000000000000000 + numberToAdd;
NSLog( #"value = %llu", numberFinal);

Storing functions in an array and applying them to an array of numbers

I've prototyped an algorithm for my iOS game in Python, and I need to rewrite in in ObjC. Basically, I have a board of 16 numbers, and I want to loop through every number three times and the four functions I'm using (add, subtract, multiply, exponentiate). 1+2+3, 2*3-4, 3^4-5, 9-4^3, etc., but without order of operations (first operation is always done first).
What I would like is an overview of how this might be implemented in Objective-C. Specifically, what is the equivalent of an array of functions in Objective-C? Is there an easy way to implement it with selectors? What's the best structure to use for loops with numbers? Array of NSIntegers, array of ints, NSArray/NSMutableArray of NSNumbers?
import random as rand
min = 0
max = 9
max_target = 20
maximum_to_calculate = 100
def multiply(x, y):
return x * y
def exponate(x, y):
return x ** y
def add(x, y):
return x + y
def subtract(x, y):
return x - y
function_array = [multiply, exponate, add, subtract]
board = [rand.randint(min, max) for i in xrange(0, 16)]
dict_of_frequencies = {}
for a in board:
for b in board:
for first_fun in function_array:
first_result = first_fun(a, b)
for c in board:
for second_fun in function_array:
final_result = second_fun(first_result, c)
if final_result not in dict_of_frequencies:
dict_of_frequencies[final_result] = 0
dict_of_frequencies[final_result] += 1
The most convenient way in Objective-C to construct an array of functions would be to use Blocks:
typedef NSInteger (^ArithmeticBlock)(NSInteger, NSInteger);
ArithmeticBlock add = ^NSInteger (NSInteger x, NSInteger y){
return x + y;
};
ArithmeticBlock sub = ^NSInteger (NSInteger x, NSInteger y){
return x - y;
};
NSArray * operations = #[add, sub];
Since there's no great way to perform arithmetic on NSNumbers, it would probably be best to create and store the board's values as primitives, such as NSIntegers, in a plain C array. You can box them up later easily enough, if necessary -- #(boardValue) gives you an NSNumber.
If you want to do it with straight C function pointers, something like this will do it:
#include <stdio.h>
#include <math.h>
long add(int a, int b) {
return a + b;
}
long subtract(int a, int b) {
return a - b;
}
long multiply(int a, int b) {
return a * b;
}
long exponate(int a, int b) {
return pow(a, b);
}
int main(void) {
long (*mfunc[4])(int, int) = {add, subtract, multiply, exponate};
char ops[4] = {'+', '-', '*', '^'};
for ( int i = 0; i < 4; ++i ) {
printf("5 %c 9 = %ld\n", ops[i], mfunc[i](5, 9));
}
return 0;
}
and gives the output:
paul#MacBook:~/Documents/src$ ./rndfnc
5 + 9 = 14
5 - 9 = -4
5 * 9 = 45
5 ^ 9 = 1953125
paul#MacBook:~/Documents/src$
Function pointer syntax can be slightly convoluted. long (*mfunc[4])(int, int) basically translates to defining a four-element array, called mfunc, of pointers to functions returning long and taking two arguments of type int.
Maddy is right. Anyway, I'll give it a try just for the fun of it.
This has never seen a compiler. So please forgive me all the typos and minor syntax errors in advance.
#include <stdlib.h>
...
const int MIN = 0;
const int MAX = 9;
const int MAX_TARGET = 20;
const int MAX_TO_CALCULATE = 100;
...
- (int) multiply:(int)x with:(int)y { return x * y; }
- (int) exponate:(int)x with:(int)y { return x ^ y; }
- (int) add:(int)x to:(int)y { return x + y; }
- (int) substract:(int)x by:(int)y { return x - y; }
// some method should start here, probably with
-(void) someMethod {
NSArray *functionArray = [NSArray arrayWithObjects: #selector(multiply::), #selector(exponate::), #selector(add::), #substract(multiply::), nil]; // there are other ways of generating an array of objects
NSMutableArray *board = [NSMutableArray arrayWithCapacity:16]; //Again, there are other ways available.
for (int i = 0; i < 16; i++) {
[board addObject:#(arc4random() % (MAX-MIN) + MIN)];
}
NSMutableDictionary dictOfFrequencies = [[NSMutableDictionary alloc] init];
for (NSNumber a in board)
for (NSNumber b in board)
for (SEL firstFun in functionArray) {
NSNumber firstResult = #([self performSelector:firstFun withObject:a withObject:b]);
NSNumber countedResults = [dictOfFrequencies objectForKey:firstResult];
if (countedResults) {
[dictOfFrequencies removeObjectForKey:firstResult];
countedResults = #(1 + [countedResults intValue]);
} else {
countedResults = #1; // BTW, using the # followed by a numeric expression creates an NSNumber object with the value 1.
}
[dictOfFrequencies setObject:countedResults forKey:firstResult];
}
}
Well, let me add some comments before others do. :-)
There is no need for objective c. You python code is iterative therefore you can implement it in plain C. Plain C is available where ever Objective C is.
If you really want to go for Objective-C here then you should forget your python code and implement the same logic (aiming for the same result) in Objective-C in an OOP style. My code really tries to translate your code as close as possible. Therefore my code is far far away from neither beeing good style nor maintainable nor proper OOP. Just keep that in mind before you think, ObjC was complicated compared to python :-)

adler32 checksum in objective c [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am working on a app which sends data to server with user location info. Server accept this data based on checksum calculation, which is written in java.
Here is the code written in Java:
private static final String CHECKSUM_CONS = "1217278743473774374";
private static String createChecksum(double lat, double lon) {
int latLon = (int) ((lat + lon) * 1E6);
String checkSumStr = CHECKSUM_CONS + latLon;
byte buffer[] = checkSumStr.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
CheckedInputStream cis = new CheckedInputStream(bais, new Adler32());
byte readBuffer[] = new byte[50];
long value = 0;
try {
while (cis.read(readBuffer) >= 0) {
value = cis.getChecksum().getValue();
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
return String.valueOf(value);
}
I tried looking for help to find out how to write objective c equivalent of this. Above function uses adler32 and I don't have any clue about that. Please help.
Thanks for your time.
The answers shown here by #achievelimitless and #user3275097 are incorrect.
First off, signed integers should not be used. The modulo operator on negative numbers is defined differently in different languages, and should be avoided when possible. Simply use unsigned integers instead.
Second, the loops will quickly overflow the 16-bit accumulators, which will give the wrong answer. The modulo operations can be deferred, but they must be done before overflow. You can calculate how many loops you can do safely by assuming that all of the input bytes are 255.
Third, because of the second point, you should not use 16-bit types. You should use at least 32-bit types to avoid having to do the modulo operation very often. You still need to limit the number of loops, but the number gets much bigger. For 32-bit unsigned types, the maximum number of loops is 5552. So the basic code looks like:
#define MOD 65521
#define MAX 5552
unsigned long adler32(unsigned char *buf, size_t len)
{
unsigned long a = 1, b = 0;
size_t n;
while (len) {
n = len > MAX ? MAX : len;
len -= n;
do {
a += *buf++;
b += a;
} while (--n);
a %= MOD;
b %= MOD;
}
return a | (b << 16);
}
As noted by #Sulthan, you should simply use the adler32() function provided in zlib, which is already there on Mac OS X and iOS.
On basis of definition of adler32 checksum as mentioned in wikipedia,
Objective C implementation would be like this:
static NSNumber * adlerChecksumof(NSString *str)
{
NSMutableData *data= [[NSMutableData alloc]init];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
for (int i = 0; i < ([str length] / 2); i++)
{
byte_chars[0] = [str characterAtIndex:i*2];
byte_chars[1] = [str characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[data appendBytes:&whole_byte length:1];
}
int16_t a=1;
int16_t b=0;
Byte * dataBytes= (Byte *)[data bytes];
for (int i=0; i<[data length]; i++)
{
a+= dataBytes[i];
b+=a;
}
a%= 65521;
b%= 65521;
int32_t adlerChecksum= b*65536+a;
return #(adlerChecksum);
}
Here str would be your string as mentioned in your question..
So when you want to calculate checksum of some string just do this:
NSNumber * calculatedChkSm= adlerChecksumof(#"1217278743473774374");
Please Let me know if more info needed

How to Increment numbers in an array to populate UIPickerView

I have a UIPickerView that I am populating with an array. It has two columns and i need the first column to go from 50-500. the second column to go from 0.01 to 1. The point is for the user to pick their weight. For doing the 50-500 I have this,
-(void)populateWeightPickerArray{
weightPickerArray = [[NSMutableArray alloc] init];
for (int weight = 50; weight <=500; weight++) {
NSString *weightString = [NSString stringWithFormat:#"%d%",weight];
[weightPickerArray addObject:weightString];
}
}
I tried doing that with the decimal, however when i use ++ it goes up by whole number and I end up getting 1.01, 2.01, 3.01 etc. here is what I have for code.
-(void)populateWeightPickerArray2{
weightPickerArray2 = [[NSMutableArray alloc] init];
for (float weightDecimal = .01; weightDecimal <= 10; weightDecimal++) {
NSString *weightDecimalString = [NSString stringWithFormat:#"%0.2f",weightDecimal];
[weightPickerArray2 addObject:weightDecimalString];
}
}
(I know i said I only needed it to go to 1 not 10, but i put 10 because at first it was only displaying 1.01, so i put 10 to test the output until I can get it right.)
So i need to somehow increment it to make it go from .01 to 1 (0.02, 0.03,0.04 etc). Anyone know how to do this?
for (float weightDecimal = .01; weightDecimal <= 10; weightDecimal = weightDecimal + 0.01)
or more succinctly:
for (float weightDecimal = .01; weightDecimal <= 10; weightDecimal += 0.01)
In Objective C: x += y is a shorthand for x = x + y.
Although you often see for loops with something++ or something-- you can use any expression.

Resources