Generate Random Number of Certain Amount of Digits

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.

Generating a random number with specific amount of digits and sum_of_digits (Python 3.8)

Simple solution

You can create a list of numbers which can be generated and then use random.choice() function to choose 1 element from list.

import random

n = int(input("Amount of digits: "))
x = int(input("Sum of digits: "))
numbers = [num for num in range(10 ** (n - 1), 10 ** n) if sum(map(int, str(num))) == x]
print(random.choice(numbers))

Fast solution

import random

t = []

def f(s, i):
r = sum(map(int, s))
if i == n:
if r == x:
t.append(s)
else:
for q in range(10) if len(s) else range(1, 10):
if r + q <= x:
f(s + str(q), i + 1)

n = int(input("Amount of digits: "))
x = int(input("Sum of digits: "))

f("", 0)
print(random.choice(t))

How to generate a random number with a specific amount of digits?

You can use either of random.randint or random.randrange. So to get a random 3-digit number:

from random import randint, randrange

randint(100, 999) # randint is inclusive at both ends
randrange(100, 1000) # randrange is exclusive at the stop

* Assuming you really meant three digits, rather than "up to three digits".


To use an arbitrary number of digits:

from random import randint

def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)

print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

Output:

33
124
5127

How to Generate a random number of fixed length using JavaScript?

console.log(Math.floor(100000 + Math.random() * 900000));

how to generate random numbers of specific digits?

You generate your randoms like this:

Random r = new Random();
int ran1 = r.nextInt(9)+1; // Will give values from 1-9
int ran2 = r.nextInt(90)+10; // Will give values from 10-99

You then create your string like this:
Opt 1 (Less recommended):

String s1 = String.valueOf(ran1);
String s2 = String.valueOf(ran2);
textSelectedFileName.setText(s1+s2);

Opt 2:

textSelectedFileName.setText(String.valueOf((ran1*100)+ran2));

Generate random numbers only with specific digits

Here is a solution using list-comprehension:

>>> random.sample([i for i in range(1,100_001) if all([int(x)%2==1 for x in str(i)])], 4)
[3115, 75359, 53159, 31771]

As pointed out in the comments below, the above code becomes more and more inefficient the larger the numbers get, due to all numbers being checked if each of them includes only odd-numbers. That includes numbers that are even.

IF we add another filter to first remove all even-numbers we reduce the amounts of comparisons that are being made by about a third.

Here is a quick comparison between the two:

import datetime
import random

def timer(var):
def wrapper(*args, **kwargs):
start = datetime.datetime.now()
result = var()
print(f"Elapsed time: {datetime.datetime.now()-start}")
return result
return wrapper

@timer
def allNumbers():
return random.sample([i for i in range(1, 1_000_001) if all([int(x) % 2 == 1 for x in str(i)])], 4)

@timer
def oddNumbers():
return random.sample([i for i in [x for x in range(1, 1_000_001) if x % 2 == 1] if all([int(x) % 2 == 1 for x in str(i)])], 4)

print("Calling allNumbers:")
print(allNumbers())
print("Calling oddNumbers:")
print(oddNumbers())

Output:

Calling allNumbers:
Elapsed time: 0:00:05.119071
[153539, 771197, 199379, 751557]
Calling oddNumbers:
Elapsed time: 0:00:02.978188
[951919, 1399, 199515, 791393]

How to generate a random number with the amount of digits, the user enters?

random.randint includes both bounders, so i think you mean random.randint(0, 9) in your example.

I suggest use math to solve your problem. n-digit number is number between 10**(n-1) and 10**n.

so it will look like this

digigts = int(digits)
num = random.randint(10**(digits - 1), 10**digits - 1)

How to create random numbers a specific number of times?

If you want to have an array full of random numbers, I suggest using the following:

int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
}

That will work and you don't even need the variable k.


Edit:

If you want to print at what position you find a specific value (for example x = 543), you can use the following code:

int x = 543;
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
if(arr[i] == x) {
System.out.println(i);
break;
}
}

Edit2

One possible solution to your new problem looks like this:

public class Feld  {
public static void main(String[] args) {
int n = 1000000;
int arr[] = new int[n];
int i = 0;
for(i = 0; i < n; i++){
arr[i] = i; //Filling array with values 0-1000000
}
int number = 20; //Print out position of a random generated number a specific amount of times
int randomNumber = (int)(Math.random()*1000001); //The random number

for(int j = 0; j < number; j++) { //Find number for a specific amount of times
for(int k = 0; k < arr.length; k++) { //Find number in array
if(arr[k] == randomNumber) {
System.out.println(arr[k]); //Print
break; //Number found, don't have to search anymore
}
}
}
}
}

Generating random whole numbers in JavaScript in a specific range

There are some examples on the Mozilla Developer Network page:

/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}

/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

Here's the logic behind it. It's a simple rule of three:

Math.random() returns a Number between 0 (inclusive) and 1 (exclusive). So we have an interval like this:

[0 .................................... 1)

Now, we'd like a number between min (inclusive) and max (exclusive):

[0 .................................... 1)
[min .................................. max)

We can use the Math.random to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting min from the second interval:

[0 .................................... 1)
[min - min ............................ max - min)

This gives:

[0 .................................... 1)
[0 .................................... max - min)

We may now apply Math.random and then calculate the correspondent. Let's choose a random number:

                Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)

So, in order to find x, we would do:

x = Math.random() * (max - min);

Don't forget to add min back, so that we get a number in the [min, max) interval:

x = Math.random() * (max - min) + min;

That was the first function from MDN. The second one, returns an integer between min and max, both inclusive.

Now for getting integers, you could use round, ceil or floor.

You could use Math.round(Math.random() * (max - min)) + min, this however gives a non-even distribution. Both, min and max only have approximately half the chance to roll:

min...min+0.5...min+1...min+1.5   ...    max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max

With max excluded from the interval, it has an even less chance to roll than min.

With Math.floor(Math.random() * (max - min +1)) + min you have a perfectly even distribution.

min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
| | | | | |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max

You can't use ceil() and -1 in that equation because max now had a slightly less chance to roll, but you can roll the (unwanted) min-1 result too.



Related Topics



Leave a reply



Submit