Random number always begins with 1 - random

I want to generate a random number between 1,000 and 9,999 and convert the return value to string. Thus I have:
(Math.floor(Math.random() * 9999) + 1000).toString()
However, this always returns me a number that starts with one. What am I doing wrong? Also, if I want to return a number where the digits are not repeated and the range is from 1 to 9999, how do I modify the equation?
A random number that didn't begin with a 1.

Related

Generate random but always different numbers within a range with CSPRNG

I have a CSPRNG that I'm using to generate 5 numbers between 0 and 20. The problem is, there could be cases where it generates the same number again. So say it generates 5 but running again, it could come out to be 5. If not, then the third or 4th number could be 5.
I want a way to do this where I'm 100% sure the 5 numbers are never the same, even if they do come up as same, I want to re-generate that number in a way that none of the numbers clash.
I thought of using a while loop for each number, to regenerate the number while it's same as the other 4 numbers but that obviously is not optimal and may cause to get stuck in long loops.
Is there a better way?
so as far as I understand that question you want a way to find N unique random numbers from your CSPRNG within the specified range and an execution time that's independant from the numbers generated from the underlying CSPRNG
make an array with your number range (here 0 to 20 => 21 elements)
run a loop for all array elements:
let idx = array index of current element
let jdx = CSPRNG(within range -1; here between 0 and 19 inclusive)
if jdx >= idx add 1 to jdx // idx and jdx are now 2 distinct array index positions
swap array elements idx and jdx
your N uniqe random numbers are the N first/last elements of the array

Pseudocode Algorithms for a few problems [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm supposed to write 5 pseudocodes for algorithms below and I'm kinda stuck. The things I've done are below the tasks, I know last 3 are meaningless. Would appreciate any help or tips. Thanks
• Printing the largest number from the input
Title: Print Largest Number From Input
//works with number inputs
max=0
number= getNumber()
read number
if number == NONE
print (“NO VALID DATA”)
while number != NONE
if number > max
max = number
• Printing the largest even integer value from the input
Title: Print Largest Even Integer Number From Input
//works with even integer inputs
max=0
integer number= getNumber()
read_integer number
if number == NONE
print “NO VALID DATA”
if number % 2 == 0
print(“NO VALID DATA”)
while number != NONE && number % 2 != 0
if number > max
max = number
• Printing the sum of all input integers
Title: Print Sum of All Input Integers
int Number= getNumber()
read_integer Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n]
• Printing the arithmetic mean of all input numbers
Title: Print Arithmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n] / n
• Printing all values greater or equal to the arithmetic mean of all input numbers
Title: Print All Values Greater Than or Equal to the Aritmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
arithmetic_mean = li[1] + li[2] + li[3] + ……. + li[n] / n
print(“”)

I'm guessing this is for class homework, so I wont provide full answers, but I'll try to help.
1. Print the largest number from the input
max = 0
// Assume that getNumber reads an input from the user and returns NONE if it is not a valid number
number = getNumber()
// If they never enter a number, give an error
if number == NONE:
print(“NO VALID DATA”)
exit() // exit the program
// Keep doing the following until number is set to NONE
while number != NONE:
if number > max:
max = number
number = getNumber()
print("The largest number is:")
print(max)
It seems like you basically have the right idea here. One thing to remember is that you have to getNumber() inside the loop. Otherwise, the value of number will never change because you only read the input once.
Note: this algorithm doesn't work if they only ever enter negative numbers. Setting max to negative infinity would fix that.
2. Print the largest even integer value from the input
This is exactly the same idea. The only change you have to make is ignoring every number that isn't even. You have the right idea for checking even-ness with the % operator.
Be careful where you make this check, though. If you check in the condition of the while loop, like you do in your code, then the loop will exit (and your program will stop) as soon as they enter an odd number. If you don't want that, then keep the loop running and just don't ever set max to be an odd number.
3. Print the sum of all input integers
It seems like your idea here is to save all the numbers they input to a list and then sum up the list at the end. That would work fine if you want to do that, but it's not necessary. Just like you kept track of a running max value, you could keep track of a running sum. Just add your the input to it each time. This is generally called the "accumulator pattern" if you want to look it up.
4. Print the arithmetic mean of all input numbers
Again, it looks like you are trying to store all the numbers in a list. Again, not necessary. Calculating the mean is just like calculating the sum except you need to divide by the number of inputs at the end. So, in addition to keeping track of the sum, you need to add an additional "accumulator" for n and just add 1 to it each time.
Also, it looks like you might be a little confused about what while does. while works just like if. It checks if a condition is true, and, if it is, it runs the code beneath it. The only difference is that while will keep running that code again and again until the condition is false. So the line while li.length == n doesn't make any sense. you haven't declared what n is before hand, so it can't make this comparison. I'm guessing you meant to do something like:
while number != NONE:
n = li.length
Here, you are assigning n to be the length of the list, instead of checking if the list length is equal to n or not.
5. Print all values greater or equal to the arithmetic mean of all input numbers
Here, we actually need to save all the inputs to a list, because we can't know what the mean is until we have seen all the numbers.
I would break this into three parts. First, just get all the input numbers and save them to a list. Then, calculate the mean of the list. Lastly, step through the list and print every value that's larger than the mean.
For part 1, just use the same pattern with a while loop that you have been since the first problem, but append number to a list instead of adding it to a sum.
For part 2, you need to calculate the sum of the list. In your code, you wrote li[1] + li[2] + li[3] + ……. + li[n]. The way you express this in code is probably with a for loop. I recommend looking up for loops for the language you are working in and seeing how they work. In some languages, you might be able to do something like this:
sum = 0
for number in list:
sum = sum + number
or, it might look like this:
sum = 0
for index in 0...list.length:
sum = sum + list[index]
For part 3, now that you have calculated the mean, you just need to loop through the numbers again and print the ones that are bigger than the mean.
for number in list:
if number > mean:
print(number)

Cypher: Match random node in Neo4j

I have a database with 3.4 millions of nodes and want to select a random node.
I tried using something like
MATCH (n)
WHERE rand() <= 0.01
RETURN n
LIMIT 1
but it seems like the algorithm always starts with the same nodes and selects the first one whose random number is below 0.01, which means in most cases the "random" node is one of the first 100 checked nodes.
Is there a better query, to select a completely random one of all my nodes?
You could generate an random ID from the rand() function and multiply it by the number of nodes. This should generally return a more random node.
MATCH (n)
WHERE id(n) = toInteger(rand() * 3400000)
Once there is some space created within your nodes (i.e. they are no longer perfectly contiguous due to deletes) you might miss a few here and there. In that case you could always range the random number +/- a few on either side and return the first row of the result.
WITH toInteger(rand() * 3400000) AS rand_node, 5 AS offset
WITH range(rand_node - offset, rand_node + offset) AS rand_range
MATCH (n)
WHERE id(n) IN rand_range
RETURN n
LIMIT 1

Generate numbers where Each pair of adjacent digits also occurs in the original number

I would like to output all similar numbers of a number, where:
Each pair of adjacent digits also occurs in the original number.
The new numbers has the same number of digits as the original
The order in which the numbers are generated doesn't matter
For example suppose I'm given a number 12314, then I have the pairs 12,23,31,14
I should generate [12314,31231,12312,23123].
If I'm given numbers like 52 or 11111 then I should get only 52/11111 respectively.
I have already written code that generates the pairs [12,23,31,14], and generate all possible permutations of this list of pairs. However, the permutations produce numbers that are longer than the original, and many of these permutations are invalid. For example, when 1214 appears in the permutation, the permutation is not valid since "21" is not in the original number.
I'd like to know how to proceed. It looks very inefficient to filter out the invalid ones from all permutations.
You could use recursion to generate the required numbers.
The idea is to maintain only valid numbers at any stage and to display when the original length and length of your number are equal.
// pairs[i][j] is true if j is immediately after i in the original number
bool pairs[10][10];
// curr_num is a valid number according to the constraint given
// curr_len is the number of digits in curr_num
// length is the number of digits in the number given
void generate(int curr_num, int curr_len, int length){
if(cur_len == length){
display curr_num;
} else {
// extract last digit & check what digits can follow that
int last = curr_num % 10;
for(int i = 0 ; i <= 9 ; i++)
if(pairs[last][i])
generate(curr_num * 10 + i , curr_len + 1, length);
}
}
for(digit in original_number)
generate(digit, 1, length);
You could optimize the code by making pairs an adjacency list than an adjacency matrix.

Efficient database lookup based on input where not all digits are sigificant

I would like to do a database lookup based on a 10 digit numeric value where only the first n digits are significant. Assume that there is no way in advance to determine n by looking at the value.
For example, I receive the value 5432154321. The corresponding entry (if it exists) might have key 54 or 543215 or any value based on n being somewhere between 1 and 10 inclusive.
Is there any efficient approach to matching on such a string short of simply trying all 10 possibilities?
Some background
The value is from a barcode scan. The barcodes are EAN13 restricted circulation numbers so they have the following structure:
02[1234567890]C
where C is a check sum. The 10 digits in between the 02 and the check sum consist of an item identifier followed by an item measure. There might be a check digit after the item identifier.
Since I can't depend on the data to adhere to any single standard, I would like to be able to define on an ad-hoc basis, how particular barcodes are structured which means that the portion of the 10 digit number that I extract, can be any length between 1 and 10.
Just a few ideas here:
1)
Maybe store these numbers in reversed form in your DB.
If you have N = 54321 you store it as N = 12345 in the DB.
Say N is the name of the column you stored it in.
When you read K = 5432154321, reverse this one too,
you get K1 = 1234512345, now check the DB column N
(whose value is let's say P), if K1 % 10^s == P,
where s=floor(Math.log(P) + 1).
Note: floor(Math.log(P) + 1) is a formula for
the count of digits of the number P > 0.
The value floor(Math.log(P) + 1) you may also
store in the DB as precomputed one, so that
you don't need to compute it each time.
2) As this 1) is kind of sick (but maybe best of the 3 ideas here),
maybe you just store them in a string column and check it with
'like operator'. But this is trivial, you probably considered it
already.
3) Or ... you store the numbers reversed, but you also
store all their residues mod 10^k for k=1...10.
col1, col2,..., col10
Then you can compare numbers almost directly,
the check will be something like
N % 10 == col1
or
N % 100 == col2
or
...
(N % 10^10) == col10.
Still not very elegant though (and not quite sure
if applicable to your case).
I decided to check my idea 1).
So here is an example
(I did it in SQL Server).
insert into numbers
(number, cnt_dig)
values
(1234, 1 + floor(log10(1234)))
insert into numbers
(number, cnt_dig)
values
(51234, 1 + floor(log10(51234)))
insert into numbers
(number, cnt_dig)
values
(7812334, 1 + floor(log10(7812334)))
select * From numbers
/*
Now we have this in our table:
id number cnt_dig
4 1234 4
5 51234 5
6 7812334 7
*/
-- Note that the actual numbers stored here
-- are the reversed ones: 4321, 43215, 4332187.
-- So far so good.
-- Now we read say K = 433218799 on the input
-- We reverse it and we get K1 = 997812334
declare #K1 bigint
set #K1 = 997812334
select * From numbers
where
#K1 % power(10, cnt_dig) = number
-- So from the last 3 queries,
-- we get this row:
-- id number cnt_dig
-- 6 7812334 7
--
-- meaning we have a match
-- i.e. the actual number 433218799
-- was matched successfully with the
-- actual number (from the DB) 4332187.
So this idea 1) doesn't seem that bad after all.

Resources