Random generation

With this post I’m starting a series where I will show you how to implement a functionality on the same topic in multiple languages.

All such posts will be marked with a tag : (multi-language)

We will start with generating random numbers and strings.

JavaScript

function rand_int(min,max=null) {
	if (max == null) { max = min; min = 0 }
	return Math.round(Math.random() * max) + min
}
const az = 'abcdefgijhklmnopqrstuvwxyzABCDEFGIJHKLMNOPQRSTUVWXYZ'
function rand_string(count,chars=az) {
	return Array.from({length:count}, (_,x) => chars[rand_int(52)]).join('')
}
function rand_nums(min,max,count) {
	return Array.from({length:count}, (_,x) => rand_int(min,max))
}
function rand_numstr(min,max,count) {return rand_nums(min,max,count).join('')}

Java

public static int rand(int max) {
	Random r = new Random();
	return r.nextInt(max);
}

public static String rand_numstr(int len) {
	StringBuilder str = new StringBuilder();
	for (int i = 0; i < len; i++) str.append(rand(10));
	return str.toString();
}

public static String rand_string(String characters, int len) {
    Random rng = new Random();
    char[] text = new char[len];
    for (int i = 0; i < len; i++) {
        text[i] = characters.charAt(rng.nextInt(characters.length()));
    }
    return new String(text);
}

public static String rand_string(int len) {
	return rand_string("ABCDEFGHIJKLMNOPQRSTUVWXYZ",len);
}

Python

import numpy as np
import string

def rand_int(min,max,count=1):
   return np.random.randint(min,max,count)
   
def rand_int2(min,max,count=1):#non-repeatable
   return np.random.choice(range(min,max),count,replace=False)
   
def rand_str(count,opt='num'):
  chars = ''
  if opt == 'lower' : chars = string.ascii_lowercase
  elif opt == 'upper' : chars = string.ascii_uppercase
  elif opt == 'str' : chars = string.ascii_letters
  elif opt == 'all' : chars = string.digits + string.ascii_letters
  else : chars = string.digits  
  return ''.join([chars[rand_int(0,len(chars))[0]] for _ in range(count) ])
   
print(rand_int(0,100,10))
print(rand_int2(0,10,10))   
print(rand_str(10))   
print(rand_str(10,'lower'))   
print(rand_str(10,'upper'))   
print(rand_str(10,'str'))
print(rand_str(10,'all'))   

------

[24 50  6 69 69 89 78 24 32  3]
[2 3 0 9 7 6 8 1 5 4]
2123149924
tzuqwomaqv
VWXNTLMUDO
wIbOSUostQ
RDwgVu9QCH