Generate a random number between negative and positive in swift [duplicate] - swift

This question already has an answer here:
How to generate a random number in a range (10...20) using Swift [duplicate]
(1 answer)
Closed 4 years ago.
So I'm trying to generate a random number between negative and positive range because I need to give an object a position on the x axis. I've tried with arc4random and arc4random_uniform but it doesn't work. I need a way to generate a random position on the x axis, negative and positive.

I don't think you can generate negative random number using arc4random directly
let lValue = -10 // (your negative number)
let uValue = 10 //(your positive number)
let result = Int(arc4random_uniform(UInt32(uValue - lValue + 1))) + lValue
print(result)
hope this will work

let min : UInt32 = 10
let max : UInt32 = 50
let randomNumber = arc4random_uniform(max - min) + min
if arc4random_uniform(2) == 0 {
randomNumber = randomNumber * -1
}

Related

Swift: Generate random number between multiple ranges

I want to generate a random number that can be between
-3...-8 and 3...8
I know I could find a roundabout way of doing this by first doing a random integer between 0 and 1 and then picking the range on that:
let zeroOrOne = CGFloat.random(in: 0...1)
if zeroOrOne == 0 {
randomNum = CGFloat.random(in: -3...-8)
} else {
randomNum = CGFloat.random(in: 3...8)
}
but I am wondering if there is a better way of doing this.
I am sure you want to use Bool.random.
One way to write it would be
let randomNum = CGFloat.random(in: 3...8) * (Bool.random() ? 1 : -1)
or
var randomNum = CGFloat.random(in: 3...8)
if Bool.random() {
randomNum.negate()
}
There is no single correct solution.
There is a general solution for generating a random integer within several nonoverlapping ranges.
Find the number of integers in each range; this is that range's weight (e.g., if each range is a closed interval [x, y], this weight is (y - x) + 1).
Choose a range randomly according to the ranges' weights (see this question for how this can be done in Swift).
Generate a random integer in the chosen range: CGFloat.random(in: range).

Calculate simple math equation [duplicate]

This question already has answers here:
How to round a Double to the nearest Int in swift?
(9 answers)
Closed 4 years ago.
I try to use swift code to calculate 10 * 75% = 7.5
var b : Int = 10
var a : Int = 75
// result x is 0
var x = b * (a / 100)
However the result is zero. How to get 7.5 result without changing the type and value of a and b?
UPDATE:
I got it right by:
var x: Double = (Double(b) * (Double(a) / 100)) // x is 7.5
Now, how can I round it to 8 as a Int type?
You're using integer (i.e. whole number) arithmetic, when what you want is floating-point arithmetic. Change one of the types to Float, and Swift will figure out that x is also a Float.
var b : Int = 10
var a : Int = 75
var x = Float(b) * (Float(a) / 100.0) // now x is a Float (.75)
For doing arithmetic in Swift, both sides of the equation must be using the same type. Try using this code:
let b = 10.0
let a = 75.0
let x = b * (a / 100.0
print(x)
7.5
To make it round up, use the built in ceil function
print(ceil(x))
8.0
Ok then you just need to do:
var b : Int = 10
let c = (Double(b) * 0.75)
let restult = ceil(c)

How do I randomize a position negatively?

So I have to randomize an x position. But for some reason the middle is 0 and therefore I need to do negative max x and positive max x. It's a little hard to explain so here is the code:
let height = UInt32(self.view!.frame.height)
let nHeight = ((height - height) - height)
let randomXPosition = Int(arc4random_uniform(UInt32(nHeight)) + height)
This doesn't give me any errors but when I run it crashes. I need a way to randomize the value for negative max X and positive max X so that the object is randomized in the screen.
If you need to generate a random number between -x and x then just create a random number between 0 and 2x and subtract x. arc4random_uniform(x * 2) - x.

Creating random number in SpriteKit

I'm trying to create a game in which a projectile is launched at a random angle.
To do this I need to be able to generate two random Int's. I looked up some tutorials and came up with this:
var random = CGFloat(Int(arc4random()) % 1500)
var random2 = CGFloat(Int(arc4random()) % -300)
self.addChild(bullet)
bullet.physicsBody!.velocity = CGVectorMake((random2), (random))
It worked for a while but now it just crashes.
Any help would be appreciated.
What I find I use the most is arc4random_uniform(upperBound) which returns a random Int ranging from zero to upperBound -1.
let random = arc4random_uniform(1500)
let random2 = arc4random_uniform(300) * -1
//pick a number between 1 and 10
let pick = arc4random_uniform(10)+1
The lowdown on the arc4 functions: arc4random man page
GameplayKit has a nice class wrapping the arc4 functions: GameplayKit Randomness
and a handy reference: Random Hipster
I dont understand very well your issue but I think it could be useful:
func getRandomPointFromCircle(radius:Float, center:CGPoint) -> CGPoint {
let randomAngle = Float(arc4random())/Float(UInt32.max-1) * Float(M_PI) * 2.0
// polar => cartesian
let x = radius * cosf(theta)
let y = radius * sinf(theta)
return CGPointMake(CGFloat(x)+center.x,CGFloat(y)+center.y)
}

Swift - arc4random() could not find an overload for '%' that accepts the supplied arguments

I have a UISlider to give a range of a radius of search (for 5 - x miles, max x=100 miles), and I want to be able to get a random radius distance within this range.
#IBAction func sliderMoved(sender: UISlider){
//gives a range (minimum range 5 miles, maximum range 5 - 100 miles)
var range = (sender.value*95)+5
//gives a random distance in miles from within that range
var distance = Int((arc4random()%(range))+1)
}
When I try to assign "distance" I get the error "could not find an overload for '%' that accepts the supplied arguments".
Use arc4random_uniform()
let distance = arc4random_uniform(UInt32(range)) - 1
arc4random_uniform() will perform the modulo operation without bias.
The problem is that the sender.value is a UISlider.value that is a Float. arc4random is a UInt32 which is your main issue here.
What you've done is try to convert the whole thing to an Int when you just need the internal components to be matching first. So get the range and the arc4random to the same type (I've done a Float here) and then do the casting you want =
Int(Float(arc4random()) % range + 1)
You of course could also use arc4random_uniform as the other commenters have stated as in :
arc4random_uniform(UInt32(range)) + 1
which is actually much better if you don't really care about the value of your range (especially any decimal part).
http://www.raywenderlich.com/forums/viewtopic.php?f=2&t=20282