Skip to main content

Generate random number in swift

Swift program for Generate random number . Here problem description and other solutions.

/*
  Swift 4 program for
  Find random number
*/
import Foundation

#if os(Linux)
    srandom(UInt32(time(nil)))
#endif
class MyNumber {
	// Print random number in given size
	func simple_random(_ size: Int) {
		var number: Int = 0;
		var i: Int = 0;
      	let max_value = UInt8.max-1 ;
		while (i < size) {
			// Get new rand number
			#if os(Linux)
              number = Int(random()) 
            #else
              number = Int(arc4random_uniform(UInt32(max_value)))
            #endif
			print(number );
			i += 1;
		}
	}
	func random_between_range(_ min: Int, _ max: Int) {
		
	  // Calculate random number
	  var number: Int = 0;
      #if os(Linux)
      	number = min + Int(random()%(max-min)) 
      #else
      	number =  Int(min + arc4random_uniform(max - min)) 
      #endif
	  print(number);
	}
}
func main() {
	let obj: MyNumber = MyNumber();
	// Test Case
	obj.simple_random(3);
	// Range from 1 to 10
	obj.random_between_range(1, 10);
	// Range from 50 to 100
	obj.random_between_range(50, 100);
	// Range from 1000 to 2000
	obj.random_between_range(1000, 2000);
}
main();

Output

1230848585
495614028
182928774
3
88
1485




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment