Objective-C Random Numbers - ios

I'm making a simple pong game. To make the ball move at the beginning of a new round, I am using
ballVelocity = CGPointMake(4 - arc4random() % 8,4 - arc4random() % 8);
However, the important part is just this:
4 - arc4random() % 8
However, there are a few problems with this: first and foremost, it doesn't really generate a random number. Only after I quit the simulator, then reopen it are new numbers generated. Secondly, I only want it to generate numbers between -4 and -2 or 2 and 4.

arc4random() is the preferred random function on the iphone, instead of rand(). arc4random() does not need seeding.
This code will generate the ranges you're interested in:
int minus2_to_minus4 = (arc4random() % 3) - 4;
int two_to_four = (arc4random() % 3) + 2;

You need to look at the rand() function. Basically, you "seed" it with a start value, and it returns a new random number every time you call it.
Or look at this question which has a full example using arc4random.

This will give you a floating point number between -4 and -2 OR 2 and 4
float low_bound = -4; //OR 2
float high_bound = -2;//OR 4
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
If you want a number in -4…-2 AND 2…4 try this:
float low_bound = 2;
float high_bound = 4;
float rndValueTemp = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
float rndValue = ((float)arc4random()/0x100000000)<0.5?-rndValueTemp:rndValueTemp;

Related

adding total sum with floating points

In xcode I am utilizing 4 utitextfields for the following chart that the user will enter a whole number, chart is the following:
Total | Win | Place | Show
34 | 4 | 5 | 3
My algorithm for this chart is the following:
-For total win * 1
-For total place * .5
-For total Show * .25
-Add the three totals into a new Float value (identified as,
float totalTrackAllTogether)
-Divide totalTrackAllTogether by the total column (identified as,
int trackTotalColum)
-Display the sum on onOffLabel.text
Here is the code portion that does not seem to work and crashes
-(void)trackRecordMath
{
int trackWinColum = [trackWin.text intValue];
int trackPlaceColum = [trackPlace.text floatValue];
int trackShowColum = [trackShow.text floatValue];
int trackTotalColum= [trackTotal.text intValue];
int trackWinTotal = trackWinColum * 1;
NSLog(#"%d", trackWinTotal);
int trackPlaceTotal = trackPlaceColum *.5;
NSLog(#"%d", trackPlaceTotal);
int trackShowTotal= trackShowColum *.25;
NSLog(#"%d", trackShowTotal);
float totalOfTrackColums = trackWinTotal + trackPlaceTotal + trackShowTotal;
float totalTrackAllTogether= (float) totalOfTrackColums / trackTotalColum;
onOffLabel.text = [[NSString alloc] initWithFormat:#"%f", totalTrackAllTogether];
}
I seem to be held up when trying to multiply floating points with whole numbers, and displaying it through onOffLabel.text. Thank you for the help!
These is basic stuff which works the same in C, C++ and Objective-C. If you do a floating-point calculation and store the result in an int, everything after the decimal point is dropped.
Furthermore, by using float instead of double you get massive rounding errors without any benefit. Instead of
int trackPlaceColum = [trackPlace.text floatValue];
write own of these:
NSInteger trackPlaceColumn = [trackPlace.text integerValue];
double trackPlaceColumn = [trackPlace.text doubleValue];
BTW. It's a column, not a colum. And you will get a crash if you divide by zero. So check whether trackTotalColumn is zero or not in your code.

Random number generation between two integers using arc4random()

I have an NSArray whose .count I store into an integer named arrayCount
I need to generate a random number from 0 to arrayCount but when I used arc4random() it generates a really large integer.
I've been doing this : int randomInt = arc4random()*arrayCount;
Which has been giving me random numbers like 12309120 and such.
Use arc4random_uniform instead, which is specifically designed to generate numbers in the range [0,n) (like array indices). It is better than simple arc4random() % n because it avoids the bias introduced by the modulo operator.
You'd use it as arc4random_uniform(arrayCount).
Try
int randomInt = arc4random() % arrayCount;
You just need to do the modulus instead
int randomInt = arc4random() % arrayCount;
This will give you values between (inclusive) 0 and arrayCount-1 or [0, arrayCount) if you prefer

Adding fractions calculation not working in IOS

I am trying to add fractions to get a value to put in for my progress bar but am just getting 0. here is what I have and what it is logging.
NSLog(#"prog::%f",self.progView.progress);
int total = self.forms.count;
float calc = (float)(self.progView.progress / total) + (1/total);
NSLog(#"calc::%f",calc);
NSLog(#"total::%d",total);
self.progView.progress = calc;
NSLog(#"prog now:%f", self.progView.progress);
Log:
prog::0.000000
calc::0.000000
total::4
prog now:0.000000
Take care of where you place your cast to float. Try changing from this:
float calc = (float)(self.progView.progress / total) + (1/total);
To this:
float calc = ((float)self.progView.progress / (float)total) + (1/(float)total);
Alternatively, make total a float rather than an int, e.g.
float total = self.forms.count;
float calc = ((float)self.progView.progress / total) + (1 / total);

iOS objective-C: using modulo on a float to get "inches" from Feet

I am trying to make a simple objective-C height converter. The input is a (float) variable of feet, and I want to convert to (int) feet and (float) inches:
float totalHeight = 5.122222;
float myFeet = (int) totalHeight; //returns 5 feet
float myInches = (totalHeight % 12)*12; //should return 0.1222ft, which becomes 1.46in
However, I keep getting an error from xcode, and I realized that the modulo operator only works with (int) and (long). Can someone please recommend an alternative method? Thanks!
Even modulo works for float, use :
fmod()
You can use this way too...
float totalHeight = 5.122222;
float myFeet = (int) totalHeight; //returns 5 feet
float myInches = fmodf(totalHeight, myFeet);
NSLog(#"%f",myInches);
Why don't you use
CGFloat myInches = totalHeight - myFeet;
As answered earlier, subtracting is the way to go. Just remember to convert the one tenths of feet to inches by multiplying with 12:
float totalHeight = 5.122222;
int myFeet = (int) totalHeight;
float myInches = (totalHeight - myFeet) * 12;

Arc4random float?

Doing this:
float x = arc4random() % 100;
returns a decent result of a number between 0 and 100.
But doing this:
float x = (arc4random() % 100)/100;
Returns 0. How can I get it to return a float value?
Simply, you are doing integer division, instead of floating point division, so you are just getting a truncated result (.123 is truncated to 0, for example). Try
float x = (arc4random() % 100)/100.0f;
You are dividing an int by an int, which gives an int. You need to cast either to a float:
float x = (arc4random() % 100)/(float)100;
Also see my comment about the modulo operator.
To get a float division instead of an integer division:
float x = arc4random() % 100 / 100.f;
But be careful, using % 100 will only give you a value between 0 and 99, so dividing it by 100.f will only produce a random value between 0.00f and 0.99f.
Better, to get a random float between 0 and 1:
float x = arc4random() % 101 / 100.f;
Even better, to avoid modulus bias:
float x = arc4random_uniform(101) / 100.f;
Alternatively, to avoid a two digits precision bias:
float x = (float)arc4random() / UINT32_MAX;
And in Swift 4.2+, you get built-in support for ranges:
let x = Float.random(in: 0.0...1.0)
In Swift:
Float(arc4random() % 100) / 100

Resources