Objective-C Random int - objective-c

Example, I have 2 ints and 1 output.
int IntNumberOne = 100;
int IntNumberTwo = 30;
NSLog(#"");
I would like the output to display just ONE of the two ints, and randomize every time this program is started.
How would that be done?

Use arc4random() function to pick number randomly:
NSLog(#"%d", arc4random()%2 ? IntNumberOne : IntNumberTwo);

Related

Something weird in for loop speed

here is a part of my program code:
int test;
for(uint i = 0; i < 1700; i++) {
test++;
}
the whole program takes 0.5 seconds to finish, but when I change it to:
int test[1];
for(uint i = 0; i < 1700; i++) {
test[0]++;
}
it will takes 3.5 seconds! and when I change the int to double, it will gets very worse:
double test;
for(uint i = 0; i < 1700; i++) {
test++;
}
it will takes about 18 seconds to finish !!!
I have to increase an int array element and a double variable in my real for loop, and it will takes about 30 seconds!
What's happening here?! Why should it takes that much time for just an increment?!
I know a floating point data type like double has different structure from a fixed point data type like int, but is it the only cause for such a big different time? and what about the second example which is also an int array element?!
Thanks
You have answered your question yourself.
float (double) operations are different from integer ones. Even if you just add 1.0f.
Your second example takes longer than the first one just because you added some pointer refernces. An array in C is -bottom down- not much different from a pointer to the first element. Accessing any element, even the first one, would cause the machine code to load the starting address of the array multiply the index (0 in this case) with the length of each member (4 or whatever bytes int has) and add that (0) to the pointer. Then it has to dereference the pointer, meaning to acutally load the value at that very address. Add one and write back the result.
A smart modern compiler should optimize this a bit. When you want to avoid this optimization, then modify the code a bit and don`t use a constant for the index.
I never tried that with a modern objective-c compiler. But I guess that this code would take much loger than 3.5s to run:
int test[2];
int index = 0;
for(uint i = 0; i < 1700; i++) {
test[index]++;
}
If that does not make much of a change then try this:
-(void)foo:(int)index {
int test[2];
for(uint i = 0; i < 1700; i++) {
test[index]++;
}
}
and then call foo:0;
Give it a try and let us know :)

"Weighted" random number generator

I'm currently using the below code to grab a random element from an array. How would I go about changing the code so that it returns an element weighted on the percentage that I want it to come up? For example, I want the element at index 0 to come up 27.4% of the time, but the element at index 7 to come up only 5.9% of the time.
NSArray *quoteArray = #[ #"quote1", #"quote2", #"quote3", #"quote4", #"quote5", #"quote6", #"quote7", #"quote8", ];
NSString *quoteString;
int r = arc4random() % [quoteArray count];
if(r<[rewardTypeArray count])
quoteString = [quoteArray objectAtIndex:r];
I would use an array of float (wrapped into NSNumber) objects.
Every object represents a percentage.In this case you would have an array of 8 objects:
Object 1: #27.5 ;
...
Object 7: #5.9 .
Then you get a random number from 1 to 100. If you want more precision you can also get a random number with the decimal part, and the precision doesn't influence the efficiency and neither the memory used.
Then when you get the number you iterate through all the array, keep track of the index and the percentage that you have. You use a float to sum all the percentages met and you stop only when the total percentage is greater on equal that the one that you have.
Example
NSArray* percentages= #[ #27.4 , ... , #5.9];
float randomNumber= arc4random_uniform(100) + (float)arc4random_uniform(101)/100;
NSUInteger n=0;
float totalPercentage= 0.0;
for(NSUInteger i=0; i<percentages.count; i++)
{
totalPercentage+= [ percentages[i] floatValue ];
if( totalPercentage >= randomNumber) // This case we don't care about
// the comparison precision
{
break;
}
n++;
}
// Now n is index that you want
The easiest way would be to generate a random number based on how fine-grained you want the percentage to be. To calculate to the tenth of a percent, you could generate between 0-1000, and 274 of the values you could randomly generate would be the first element. 59 values would correspond to element 7.
For example:
0-273 = index 1 27.4%
274-301 = index 2 2.7%
302-503 = index 3 20.1%
504-550 = index 4 4.6%
551-700 = index 5 14.9%
701-941 = index 6 24%
942-1000 = index 7 5.9%
The percentages don't add up properly, so I did my math wrong somewhere, but you get the point.
You can make another array with counter that would keep tracking how many times each one of your elements is being generated. If that counter is less than your target let that index come in your r, otherwise regenarate.

Getting a values most significant digit in Objective C

I currently have code in objective C that can pull out an integer's most significant digit value. My only question is if there is a better way to do it than with how I have provided below. It gets the job done, but it just feels like a cheap hack.
What the code does is that it takes a number passed in and loops through until that number has been successfully divided to a certain value. The reason I am doing this is for an educational app that splits a number up by it's value and shows the values added all together to produce the final output (1234 = 1000 + 200 + 30 + 4).
int test = 1;
int result = 0;
int value = 0;
do {
value = input / test;
result = test;
test = [[NSString stringWithFormat:#"%d0",test] intValue];
} while (value >= 10);
Any advice is always greatly appreciated.
Will this do the trick?
int sigDigit(int input)
{
int digits = (int) log10(input);
return input / pow(10, digits);
}
Basically it does the following:
Finds out the number of digits in input (log10(input)) and storing it in 'digits'.
divides input by 10 ^ digits.
You should now have the most significant number in digits.
EDIT: in case you need a function that get the integer value at a specific index, check this function out:
int digitAtIndex(int input, int index)
{
int trimmedLower = input / (pow(10, index)); // trim the lower half of the input
int trimmedUpper = trimmedLower % 10; // trim the upper half of the input
return trimmedUpper;
}

get an integer -unit digit in a simple way

i am not sure about my english, but i need to get the unit digit of an integer.
WITHOUT complex algorithm but with some API or another trick.
for example :
int a= 53;
int b=76;
this i add because i almost always dont "meet the quality standards" to post! its drive me crazy! please , fix it ! it took me 10 shoots to post this,and other issue also.
i need to get a=3 and b=6 in a simple smart way.
same about the other digit.
thanks a lot .
here is how to split the number into parts
int unitDigit = a % 10; //is 3
int tens= (a - unitDigit)/10; //is 53-3=50 /10 =5
You're looking for % operator.
a=a%10;//divides 'a' by 10, assigns remainder to 'a'
WARNING
here is how to divine the number into parts
int unitDigit = a % 10; //is 3
int tens= (a - unitDigit)/10; //is 53-3=50 /10 =5
this answer is totally incorrect. It may work only in a number of cases. For example try to get the first digit of 503 via this way
It seems the simplest answer (but not very good in performance):
int a = ...;
int digit = [[[NSString stringWithFormat:#"%d", a] substringToIndex:1] intValue]; //or use substringWithRange to get ANY digit
Modulo operator will help you (as units digit is a reminder when number is divided by 10):
int unitDigit = a % 10;
The following code "gets" the digits of a given number and counts how many of them divide the number exactly.
int findDigits(long long N){
int count = 0;
long long newN = N;
while(newN) // kinda like a right shift
{
int div = newN % 10;
if (div != 0)
if (N % div == 0) count++;
newN = newN / 10;
}
return count;
}

Randomly pick between 2 defined ints

Is there a method in objective-c that allows you to pseudorandomly decide between two ints? Or is there a quick way to implement this?
Use the following:
int number = arc4random() % 2;
if(number==0){
//pick one number
}else{
//pick other number
}
randomSelection = arc4random() % 2 ? choice1 : choice2;
in C++ that would be result = rand() < 0.5 ? int1 : int2
why can't you build the same command in ObjC?