Swift arc4random_uniform(max) in Linux
Swift 4.2
let random = Int.random(in: 0...100)
https://developer.apple.com/documentation/swift/int/2995648-random
PS. It works in Linux.
Random Alphanumeric String Linux Swift 3
Figured it out.
So the answer to the repeating random number/string was to just add this line before i called the random() function
srand(UInt32(time(nil)))
and I'm assuming thats what fixed the illegal instruction also. Because i don't recall changing anything else.
Needless to say here is my final result
func generateRandomNumber() -> Int
{
var place = 1
var finalNumber = 0;
#if os(Linux)
srand(UInt32(time(nil)))
for _ in 0..<5
{
place *= 10
let randomNumber = Int(random() % 10) + 1
finalNumber += randomNumber * place
}
#else
for _ in 0..<5
{
place *= 10
let randomNumber = Int(arc4random_uniform(10))
finalNumber += randomNumber * place
}
#endif
return finalNumber
}
func randomString(_ length: Int) -> String
{
let letters : String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = letters.characters.count
var randomString = ""
#if os(Linux)
srand(UInt32(time(nil)))
for _ in 0..<length
{
let randomValue = (random() % len) + 1
randomString += "\(letters[letters.index(letters.startIndex, offsetBy: Int(randomValue))])"
}
#else
for _ in 0 ..< length
{
let rand = arc4random_uniform(UInt32(len))
randomString += "\(letters[letters.index(letters.startIndex, offsetBy: Int(rand))])"
}
#endif
return randomString
}
Generating random numbers with Swift
let randomIntFrom0To10 = Int.random(in: 1..<10)
let randomFloat = Float.random(in: 0..<1)
// if you want to get a random element in an array
let greetings = ["hey", "hi", "hello", "hola"]
greetings.randomElement()
Swift random number problems
When you have type problems, build up your expression step by step.
import Darwin
let cs = 100
let rd = 40
let min = UInt32(0.175 * Float(rd))
let max = UInt32(0.25 * Float(cs))
// This isn't really necessary, the next line will crash if it's not true, but
// just calling out this implicit assumption
assert(max >= min)
let randomMovement = Int(arc4random_uniform(max - min) + min)
arc4random_uniform
takes a UInt32
, so you need to get there. You can't multiply Float
and Int
without a typecast, so you need to add those.
When I say "build up step-by-step" I mean for you, not the compiler. The compiler can handle:
let randomMovement = Int(arc4random_uniform(UInt32(0.25 * Float(cs)) - UInt32(0.175 * Float(rd))) + UInt32(0.25 * Float(cs)))
but it's a bit hard to understand (and may compute cs/4 twice).
Swift system version checking on Ubuntu
In Swift, #if ... #endif
are not preprocessor statements, but
enclose a "Conditional Compilation Block". The valid arguments for the os()
platform condition
are (currently) documented as
macOS, iOS, watchOS, tvOS, Linux
Therefore #if os(Linux)
checks for a Linux platform.
A typical example is
#if os(Linux)
import Glibc
#else
import Darwin
#endif
to import functions from the C library on both Linux and Apple platforms.
Swift random float between 0 and 1
Try initializing the divisor as a float as well, a la:
CGFloat(Float(arc4random()) / Float(UINT32_MAX))
Generate random number of certain amount of digits
Here is some pseudocode that should do what you want.
generateRandomNumber(20)
func generateRandomNumber(int numDigits){
var place = 1
var finalNumber = 0;
for(int i = 0; i < numDigits; i++){
place *= 10
var randomNumber = arc4random_uniform(10)
finalNumber += randomNumber * place
}
return finalNumber
}
Its pretty simple. You generate 20 random numbers, and multiply them by the respective tens, hundredths, thousands... place that they should be on. This way you will guarantee a number of the correct size, but will randomly generate the number that will be used in each place.
Update
As said in the comments you will most likely get an overflow exception with a number this long, so you'll have to be creative in how you'd like to store the number (String, ect...) but I merely wanted to show you a simple way to generate a number with a guaranteed digit length. Also, given the current code there is a small chance your leading number could be 0 so you should protect against that as well.
Creating random number in SpriteKit
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)
}
Related Topics
How to Implement a Spritekit Timer
Adding Activity Indicator to Uialertview
Healthkit Error: Missing Com.Apple.Developer.Healthkit Entitlement
Swift Uisearchcontroller Wired Up in Core Data Project, App Runs, But Search Not Updating
How to Implement a Thread Safe Hashtable (Phonebook) Data Structure in Swift
Why Are Iboutlets Optionals After Swift 5 Migration
Swift Draw Shadow to a Uibezier Path
Building User Database Model in Firebase
Dispatchqueue:Cannot Be Called with Ascopy = No on Non-Main Thread
iOS - Arkit Node Disappear After 100M
Create PDF of Dynamic Size with Typography Using Uiview Template(S)
Scenekit Object Between Two Points
Creating a Sliding Segue in Swift
Format Float Value with 2 Decimal Places
Cannot Assign to Property: 'Self' Is Immutable, I Know How to Fix But Needs Understanding