Random numbers are important in almost any programming paradigm. For example, in neural network, sometimes we need to initialise random weights. In game development, random generators are considered as God.
Here, we will quickly go through creating a random number in some common programming languages.
Random in C/C++
#include <stdio.h> #include <stdlib.h> int main () { int r; r = rand() return(0); }
Random in C#
using System; public class Class1 { public static void Main() { random = new Random(); int randomNumber = random.Next(0, 100); } }
Random in Kotlin
@Test fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() { val randomDouble = Math.random() //create a list of numbers, shuffle it //and then take the first element val randomInteger = (1..12).shuffled().first() }
Random in Java
Similar to C#, to generate a random number, use Random class from util library.
import java.util.Random; public static void main(String.. args){ int rand1 = new Random().nextInt(); double rand2 = new Random().nextDouble(); }
Random in Python
import random aInt = random.randint(1,101) aFloat = random.random()
Random in Swift
Swift 4.2+ makes it easier to generate a random number.
let number = Int.random(in: 0 ... 10) let number2 = Double.random(in: 10.0..<20.0)
Random in Dart
import 'dart:math'; main() { var rng = new Random(); for (var i = 0; i < 10; i++) { print(rng.nextInt(100)); } }
Random in JavaScript/React.JS
var maxNumber = 45; var randomNumber = Math.floor((Math.random() * maxNumber) + 1);