xxxxxxxxxx
47
/*
This program computes all possible alphanumeric passwords of
length three, using only very basic JS so that new programmers
can understand the code.
However, with recent built-in JS functions, it's
possible to compute the Cartesian product of arbitrarily
many arrays in just one line of code. See
https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript
In the solution given there, n-tuples are represented as arrays
of length n, so it would need to be modified to return passwords
of length n as strings.
*/
let pass1; //array of 1-character passwords
let pass3; //array of 3-character passwords
pass1 = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
];
//returns Cartesian product of two arrays of strings
//arr1 = [x1, ... , xm] and arr2 = [y1, ..., yn],
//with the ordered pair (x,y) represented as 'xy'
function cartesian(arr1, arr2) {
let product = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
product.push(arr1[i]+arr2[j]);
}
}
return product;
}
pass3 = cartesian(cartesian(pass1, pass1), pass1);
//check we have 36 ** 3 = 46656 passwords
console.log(pass3.length);
//log a random password
let randomIndex = Math.floor(Math.random() * pass3.length);
console.log(pass3[randomIndex]);