How to concatenate two numbers in Objective-C - objective-c

How can I concatenate two numbers like 7 and 6 to result in the number 76, or 3 and 3 so the result is 33, in objective-c?

There is no built in symbol to concatenate numbers. However, you can accomplish this by doing:
int first; /* Assuming this is initialized to the first number */
int second; /* Assuming this is initalized to the second number */
int myVal = [[NSString stringWithFormat:#"%d%d",first, second] intValue];

FirstNum * 10 + secondNum :-)

That's not a numeric operation, it's string concatenation.
Shortcuts in Objective-C to concatenate NSStrings

If you want two numbers x and y to add to xy, you can do
10*x + y.
For 7 and 6
7*10 + 6 = 76

I don't know much about objective-c but I would say:
If you get the numbers from an array, like nums= array(7,6), initialize result= 0 and then do a foreach on them. For each value you find, do : res= res*10 + value. At the end, even if you got 7 numbers to concatenate you'll get the result right. ie:
Array nums= Array(7,6,8,9);
int res= 0;
int value;
foreach (value in nums)
res= res*10 + value;
If you can use strings, just concatenate them like suggested above. there is probably a function to concatenate all values from an array as well to make it flexible.
Hope it helps
C^

Related

How to combine 2 different integers to create a single float (or a double)

I'm Cesare from Italy (please excuse my english), this is my first question posted on StackOverflow and I'm pretty new to Objective-C... I hope I won't make a mess on my first try.
I would like to "combine" two integers that I already have to create a new float (or a double).
By "combine", I mean that I'd like to have the first int before the point and the second int after the point, I'm not trying to convert from int to float. Maybe an example could explain better what I'm trying to do:
First int: 7
Second int: 92
The float I'm trying to get: 7.92
I looked for a previous question like mine but I haven't found anything, maybe because what I'm trying to do is pretty dumb (I have a UIPickerView with 2 components, each containing hundreds of integers, and I'm trying to create a float or double variable that has the selection of the first component before the point and the selection of the second component after the point).
Thanks in advance for your help,
Cesare
Just think about what the definition and/or the purpose of the decimal point is. It separates the part of the number which is less than one from the part greater than or equal to one.
So, keep dividing the part after the decimal point until it's less than 1:
int firstPart = 7;
int secondPart = 92; // or whatever
float f = secondPart;
while (f >= 1) {
f /= 10;
}
f += firstPart;
I know this is later, but came across a similar situation. Maybe this is more efficient.
Take the second number, 92 and divide it by 100. That gives you .92. Add that to the first number. That can give you 7.92. However, since you're adding integers that you want converted to a float, you'll need to cast the numbers when adding them. Like this:
int firstPart = 7;
int secondPart = 92;
float afterDecimalPlace = (float)secondPart/100.0;
float numberAsFloat = (float)firstPart + afterDecimalPlace;
essentially that is:
92/100 = .92
7 + .92 = 7.92

How to Convert Every Letter in the Alphabet To an Integer - Objective-C

I am trying to convert every letter in the alphabet to an integer like this
A = 1;
B = 2;
...
Z = 26;
I went through some forum questions but none of them worked well. Is there a way of doing this without Arrays?
for lowercase letters you need to subtract 96 from its value. Like this:
int a = 'a' - 96; // 1
for uppercase ones subtract 64. Like this:
int A = 'A' - 64;// 1
This will work for any letter of English alphabet

finding the closest Int value from a set of int values in objective c

objective c math function question
I've got a x value that i'd like to compare to other values within a set, then determine which value from the set my x value is closest to.
For example, lets say i've got the ints 5, 10, 15, 20, 25.
What is the best way to determine which of these numbers is closest to 7?
int closestDistance = INT32_MAX;
int indexOfClosestDistance = -1;
int x = 7;
for (int i=0; i < [yourArray count]; i++)
{
int num = yourArray[i];
int diff = abs(num - x);
if (diff < closestDistance)
{
closestDistance = diff;
indexOfClosestDistance = i ;
}
}
Best of luck
Neither Objective-C nor Cocoa provides anything that solves this for you. You can store your ints in a plain old array of int, or you can wrap each one in an NSNumber and store the wrappers in an NSArray.
If you're going to probe the array many times, sort it once in advance, and then for each probe use a binary search (standard C function bsearch or Core Foundation's CFArrayBSearchValues or Cocoa's -[NSArray indexOfObject:inSortedRange:options:usingComparator:]) to find the nearest two elements. If you're only going to probe the array once or twice, just use a for loop, subtraction, abs, and MIN.
The easiest way is subtract the smaller number from the larger one. So you'd want to compare the two numbers first, then just do simple subtraction. So you'd see the 10-7 is 3 away, and 7-5 is only 2 away.

How to do string related problem

I am making a binary to decimal number converter on iphone. having some problem when i trying to take each single digit from a number and do calculation. I tried char, characterAtIndex but they all failed to do calculation or i got the syntax completely wrong. Can anyone show me how to do such cast or there is an easier approach?
Your problem is getting numbers from strings?
The easiest way to get an integer from a character is to use the ascii table, like this:
NSString *stringOfNums = #"15";
char c;
int num;
for (int i = 0; i < [stringOfNums length]; ++i) {
c = [stringOfNums characterAtIndex:i];
num = c - 48; // 0 is 48 in ascii table
printf("\nchar is %c and num is %d", c, num);
}
The advantage of this method is that you can validate on a char-by-char basis that each falls in a range of 48 through 57, the ascii digits.
Or you could do the conversion in one step using NSNumberFormatter, as described here: How to convert an NSString into an NSNumber
As for the binary-decimal conversion, does your formula work on paper? Get that right first.

Objective C - Random results is either 1 or -1

I am trying randomly generate a positive or negative number and rather then worry about the bigger range I am hoping to randomly generate either 1 or -1 to just multiply by my other random number.
I know this can be done with a longer rule of generating 0 or 1 and then checking return and using that to either multiply by 1 or -1.
Hoping someone knows of an easier way to just randomly set the sign on a number. Trying to keep my code as clean as possible.
I like to use arc4random() because it doesn't require you to seed the random number generator. It also conveniently returns a uint_32_t, so you don't have to worry about the result being between 0 and 1, etc. It'll just give you a random integer.
int myRandom() {
return (arc4random() % 2 ? 1 : -1);
}
If I understand the question correctly, you want a pseudorandom sequence of 1 and -1:
int f(void)
{
return random() & 1 ? 1 : -1;
// or...
// return 2 * (random() & 1) - 1;
// or...
// return ((random() & 1) << 1) - 1;
// or...
// return (random() & 2) - 1; // This one from Chris Lutz
}
Update: Ok, something has been bothering me since I wrote this. One of the frequent weaknesses of common RNGs is that the low order bits can go through short cycles. It's probably best to test a higher-order bit: random() & 0x80000 ? 1 : -1
To generate either 1 or -1 directly, you could do:
int PlusOrMinusOne() {
return (rand() % 2) * 2 - 1
}
But why are you worried about the broader range?
return ( ((arc4random() & 2) * 2) - 1 );
This extra step won't give you any additional "randomness". Just generate your number straight away in the range that you need (e.g. -10..10).
Standard rand() will return a value from this range: 0..1
You can multiply it by a constant to increase the span of the range or you can add a constant to push it left/right on the X-Axis.
E.g. to generate random values from from (-5..10) range you will have:
rand()*15-5
rand will give you a number from 0 to RAND_MAX which will cover every bit in an int except for the sign. By shifting that result left 1 bit you turn the signed MSB into the sign, but have zeroed-out the 0th bit, which you can repopulate with a random bit from another call to rand. The code will look something like:
int my_rand()
{
return (rand() << 1) + (rand() & 1);
}