Generating unique 6 digit code js - javascript

I am trying to generate 6 digit code using JS.
it must contains 3 digits and 3 chars.
here is my code
var numbers = "0123456789";
var chars = "acdefhiklmnoqrstuvwxyz";
var string_length = 3;
var randomstring = '';
var randomstring2 = '';
for (var x = 0; x < string_length; x++) {
var letterOrNumber = Math.floor(Math.random() * 2);
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
for (var y = 0; y < string_length; y++) {
var letterOrNumber2 = Math.floor(Math.random() * 2);
var rnum2 = Math.floor(Math.random() * numbers.length);
randomstring2 += numbers.substring(rnum2, rnum2 + 1);
}
var code = randomstring + randomstring2;
the code result will be 3chars + 3 numbers .. I want to just rearrange this value to be random value contains the same 3 chars and 3 numbers
http://jsfiddle.net/pgDFQ/101/

You could shuffle your current codes with a function like this (from this answer)
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
You could use it like this:
alert(shuffle("StackOverflow".split('')).join(''));
Here is an updated demo with this code.

Here is the code for you
function(count){
var chars = 'acdefhiklmnoqrstuvwxyz0123456789'.split('');
var result = '';
for(var i=0; i<count; i++){
var x = Math.floor(Math.random() * chars.length);
result += chars[x];
}
return result;
}

what you can do is use a dingle loop from 6 times and use random character and random number function one by one while also incrementing by 1, Although not that a good option but this may also offer some flexibility

Try this:
var numbers = "0123456789";
var chars= "acdefhiklmnoqrstuvwxyz";
var code_length = 6;
var didget_count = 3;
var letter_count = 3;
var code = '';
for(var i=0; i < code_length; i++) {
var letterOrNumber = Math.floor(Math.random() * 2);
if((letterOrNumber == 0 || number_count == 0) && letter_count > 0) {
letter_count--;
var rnum = Math.floor(Math.random() * chars.length);
code += chars[rnum];
}
else {
number_count--;
var rnum2 = Math.floor(Math.random() * numbers.length);
code += numbers[rnum2];
}
}
I might note that such a code should not be considered truly random as the underlying functions could be predictable depending on the javascipt engine running underneath.

Related

brute force polynomial evaluation algorithm javascript

what is required is a brute force algorithm, and not some other!
I'm trying to implement the brute force method for a polynomial in javascript, but an error occurs, the answer is different from the other method above (horner method) - this method is checked and it gives the correct answer
but here is the second brut force- method that gives an excellent result, which is not correct.
What is the error in my code?
input :
_x = 6 _n = 5 polyEval = [2,3,5,-6,2]
output Horner method:
3386 // good. correct answer
output Bruforce method:
1496 // bad. incorrect answer
class Programm {
constructor(x:number, n:number) {
this._x = 4;
this._n = 5;
this.polyEval = [2,3,5,-6,2] //this.RandomArray(this._n);
}
private _x:number;
private _n:number;
private polyEval:number[] = [];
//working method
private Horner(poly:number[], n:number, x:number){
let time = performance.now();
let result = poly[0];
for (let i = 1; i < n; i++){
result = result * x + poly[i];
}
time = performance.now() - time;
console.log("Method: Horner |" ,`Result: ${result}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
}
// method with an error that I can't find
private BruteForce(poly:number[], n:number, x:number){
let time = performance.now();
let p: number = 0;
for(let i = n - 1; i >= 0; i--){
let coefficient = 1;
for(let j = 1; j <= i; j++){
coefficient = coefficient * x;
}
p = p + poly[i] * coefficient;
}
time = performance.now() - time;
console.log("Method: Brute Force |" ,`Result: ${p}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
}
// generate random array
private RandomArray(n: number):number[]{
let result:number[] = new Array(n);
for (let i = 0; i < n; i++){
if(Math.round(Math.random() * 1) > 0){
result[i] = Math.floor(Math.random() * (10 - 1)) + 1;
}else{
result[i] = Math.floor(((Math.random() * (10 - 1)) + 1) * -1);
}
}
return result;
}
public Main() {
console.log(`n - array length: ${this._n} | x - coefficient: ${this._x}`);
this.Horner(this.polyEval, this._n, this._x);
this.BruteForce(this.polyEval, this._n, this._x);
}
}
const random_N:number = Math.floor(Math.random() * (5 - 1)) + 3;
const random_X:number = Math.floor(Math.random() * (5 - 1)) + 2;
const poly = new Programm(random_N, random_X);
poly.Main();
The Horner's scheme works like this:
// initially
result = poly[0] == p_0;
// iteration 1
result = result * x + poly[1] == p_0 * x + p_1
// iteration 2
result = result * x + poly[2] == (p_0 * x + p_1) * x + p_2
== p_0 * x^2 + p_1 * x + p_2
Thus, the polynomial coefficients in the array poly are in order of highest to lowest. Then to replicate that in the brute force solution, one needs to apply the formula as
result = sum(poly[i] * pow(x, n-1-i)) ==
result = sum(poly[n-1-i] * pow(x, i))

Java script random number with allowed to 2 repeat value

How to create the random number to assign in java script array with following condition.
need to create random number with (1-28).
Number allowed to repeat 2 times. (EX: 1,3,5,4,5). .
Simple solution for adding a number to an array based on your criteria:
function addNumberToArray(arr){
const minValue = 1;
const maxValue = 28;
if(arr.length==maxValue*2){ //no possible numbers left
return;
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function isValueInArrayLessThenTwoTimes(value, arr){
var occurrences = 0;
for(var i=0; i<arr.length; i++){
if(arr[i]===value){
occurrences++;
}
}
return occurrences<2;
}
var newValue;
do {
newValue = getRandomArbitrary(minValue,maxValue);
} while(!isValueInArrayLessThenTwoTimes(newValue, arr));
arr.push(newValue);
}
A shorter and faster solution:
min=1;
max=28;
nums= new Array();
for(i=1;nums.length<28;i++){
a = Math.round(Math.random()*(max-min+1)+min);
if(nums.indexOf(a)==-1 || nums.indexOf(a)==nums.length-nums.reverse().indexOf(a)-1){
if(nums.indexOf(a)>-1){
nums.reverse();
}
nums.push(a);
}
}
console.log(nums);
https://jsfiddle.net/znge41fn/1/
var array = [];
for (var i = 0; i < 28; i++) {
var randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
while (getCount(array, randomNumberBetween1and28) > 2) {
randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
}
array.push(randomNumberBetween1and28);
}
function getCount(arr, value) {
var count = 1;
for (var i = 0; i < arr.length; i++) {
if (value == arr[i]) count++;
}
return count;
}

Generating alphanumerical sequence javascript

I have written a terribly slow function for generating codes that go from AA000 to ZZ999 (in sequence not random). And I have concluded that there has to be a better way to do this. Any suggestions on how to make this faster?
function generateAlphaNumeric(){
theAlphabet = ['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'];
resultArrray = [];
resultArrray2 = [];
teller = 0;
for(i in theAlphabet){
for(x in theAlphabet){
resultArrray[teller] = theAlphabet[i] + theAlphabet[x];
teller++;
}
}
teller = 0;
for(x = 0; x<10; x++){
for(y = 0; y<10; y++){
for(z = 0; z<10; z++){
resultArrray2[teller] = x.toString() + y.toString() +z.toString();
teller++;
}
}
}
teller = 0;
finalArray = [];
for(index in resultArrray){
for(i in resultArrray2){
finalArray[teller] = resultArrray[index] + resultArrray2[i];
teller++;
}
}
//console.log(resultArrray);
//console.log(resultArrray2);
console.log(finalArray);
}
This should be considerably faster:
var theAlphabet = ['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'];
var theDigits = ['0','1','2','3','4','5','6','7','8','9'];
var result = [];
for (var i=0 ; i<26 ; i++) {
var prefix1 = theAlphabet[i];
for (var j=0 ; j<26; j++) {
var prefix2 = prefix1 + theAlphabet[j];
for(var x = 0; x<10; x++){
var prefix3 = prefix2 + theDigits[x];
for(var y = 0; y<10; y++){
var prefix4 = prefix3 + theDigits[y];
for(var z = 0; z<10; z++){
result.push(prefix4 + theDigits[z]);
}
}
}
}
}
Key ideas:
Generate everything in one run
Reuse partial strings as much as possible
However, I don't see how such an exhaustive list is useful. There are exactly 26 * 26 * 1000 different codes. So instead of maintaining an array with all codes it could make sense to simply build a function that generates the specific code requested:
function getCode(number) {
var z = number % 10;
number -= z; number /= 10;
var y = number % 10;
number -= y; number /= 10;
var x = number % 10;
number -= x; number /= 10;
var a = number % 26;
number -= a; number /= 26;
var b = number;
return theAlphabet[a] + theAlphabet[b] + theDigits[x] + theDigits[y] + theDigits[z];
}
function generate() {
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
array = [];
for (var i = 0; i < str.length; i++) {
for (var j = 0; j < str.length; j++) {
for (var k = 0; k < 10; k++) {
for (var l = 0; l < 10; l++) {
for (var m = 0; m < 10; m++) {
ar.push(str[i] + str[j] + k + l + m);
}
}
}
}
}
return array;
}
console.log(generate());
This will generate a array of all the codes .. U can save that array and parse it easily using a loop.
Try this solution:
function generate() {
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
ar = [];
for (var index1 = 0; index1 < str.length; index1++) {
for (var index2 = 0; index2 < str.length; index2++) {
for (var index3 = 0; index3 < 1000; index3++) {
ar.push(str[index1] + str[index2] + ('000' + index3).slice(-3));
}
}
}
return ar;
}
console.log(generate());
I didn't test it, but it should do the trick
function generateAlphaNumeric()
{
var theAlphabet = ['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'];
var result = [];
// Will take a random letter inside theAlphabet
// Math.floor(Math.random() * theAlphabet.length) will generate a random number between 0 and 25
var i = 0;
while(i<2)
{
var letter = theAlphabet[Math.floor(Math.random() * theAlphabet.length)];
result.push(letter);
i++;
}
i = 0;
while(i<3)
{
// Adds a random number between 0 and 9
result.push(Math.floor(Math.random() * 10));
i++;
}
return result;
}
From a computational complexity perspective, unfortunately this is the best you can do. From a sheer number of instructions perspective, you can do a bit better (as others have pointed out), but it's still going to be the same order of complexity (remember that constants / multipliers are irrelevant in big-O complexity). You can also optimize the storage a bit.
Think about it. Your array needs to have 26 * 26 * 10 * 10 * 10 members. This means you need to at least touch that many elements.
Let N = number of elements in the alphabet
Let M = number of elements in your digit queue
Best Case Order Complexity = O(N * N * M * M * M) (if all you had to do was assign values)
Best case storage complexity = same as above (you have to store all the codes)
Right now you are using the following operations:
for(i in theAlphabet){ // *O(N)*
for(x in theAlphabet){ // *O(N)*
resultArrray[teller] = theAlphabet[i] + theAlphabet[x];// *(O(1))*
}
}
for(x = 0; x<10; x++){ // O(M)
for(y = 0; y<10; y++){ // O(M)
for(z = 0; z<10; z++){ // O(M)
resultArrray2[teller] = x.toString() + y.toString() +z.toString(); // O(1) (technically this is O(length of x + y + z)
teller++;
}
}
}
for(index in resultArrray){ // O(N * N)
for(i in resultArrray2){ // O(M * M * M(
finalArray[teller] = resultArrray[index] + resultArrray2[i]; //O(1)
teller++;
}
}
So at the end of the day your order complexity is O(N * N * M * M * M), which is the best you can do.
The bigger question is why you want to generate all the codes at all. If all you want is to create a unique code per order number or something, you can make a state machine like:
function getNextCode(previousCode) {
// in here, just increment the previous code
}
If all you want is a random identifier, consider using a hash of the timestamp + something about the request instead.
If you don't care about uniqueness, you can always just generate a random code.
All of the above are O(1).

Generate a random 4 digit number with no repeating digits

I have this function to create a random 4 digit number:
generateCode = function(){
var fullNumber = [];
var digit1 = Math.floor(Math.random() * 9) + 1;
var digit2 = Math.floor(Math.random() * 9) + 1;
var digit3 = Math.floor(Math.random() * 9) + 1;
var digit4 = Math.floor(Math.random() * 9) + 1;
fullNumber.push(digit1, digit2, digit3, digit4);
this.theCode(fullNumber.join("")) ;
}
But I need to create a 4 digit random number with no repeating digits.
So "1234" or "9673". But not "1145" or "5668"
Is there an efficient way to do this?
You can use this handy shuffle function to shuffle an array containing the numbers, and pick the first 4.
function random4Digit(){
return shuffle( "0123456789".split('') ).join('').substring(0,4);
}
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
alert( random4Digit() );
Edit: If you actually want a Number not starting with 0:
function random4DigitNumberNotStartingWithZero(){
// I did not include the zero, for the first digit
var digits = "123456789".split(''),
first = shuffle(digits).pop();
// Add "0" to the array
digits.push('0');
return parseInt( first + shuffle(digits).join('').substring(0,3), 10);
}
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
alert( random4DigitNumberNotStartingWithZero() );
Create an array of numbers, randomize it, then slice out the first 4 and join them together.
var numbers = [0,1,2,3,4,5,6,7,8,9];
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
shuffleArray(numbers).slice(0,4).join('');
It really depends on how you'd like to approach the problem. One solution is to store the digits you've used already in an array, then search the array when you generate a number. If the generated number is contained in the array, then you try generating another number. Doing a few different steps like this is also easier to follow if you have a few different functions. See my included example below:
var checkRandomUsed = function(array, number){
return array.indexOf(number) > -1;
}
var getCheckedRandom = function(array){
var random = getRandomNum();
while (checkRandomUsed(array, random)){
random = getRandomNum();
}
return random;
}
var getRandomNum = function(){
return Math.floor(Math.random() * 9) + 1;
}
var generateCode = function(){
var usedNumbers = [];
for (var i = 0; i < 4; i++){
usedNumbers.push(getCheckedRandom(usedNumbers));
}
return usedNumbers.join("");
}
As an update, try this...
const value = (new Array(4))
.map(() => (Math.floor(Math.random() * 9) + 1).toString()).reduce((p, c) => p + c);
This will do it if you're ok with potentially having 0 as the first digit:
var getNum = () => randoSequence(0, 9).slice(-4).join("");
console.log(getNum());
<script src="https://randojs.com/1.0.0.js"></script>
This will do it without 0 as the first digit:
function getNum(){
var sequenece = randoSequence(0, 9).slice(-4);
return (sequenece[6] ? sequenece.slice(-4) : sequenece.slice(0, 4)).join("");
}
console.log(getNum());
<script src="https://randojs.com/1.0.0.js"></script>
Both of these codes use rando.js to simplify the randomness and make it more readable, so don't forget to add the script tag to the head of your HTML document if you want to use either of them.

How I do alphanumeric in-sequence order using javascript

I'm using the following JavaScript. The final result is display sequence character.
But I want to display alphanumeric in-sequence order. How do I do that?
var disp = '';
var string = '';
var i;
var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
var ran_unrounded;
var ran_number;
var rnum;
for (i = 0; i < 5; i++) {
rnum = Math.floor(Math.random() * chars.length);
string += chars.substring(rnum, rnum + 1);
ran_unrounded = Math.random() * 3;
ran_number = Math.floor(ran_unrounded);
//document.write(chars.substring(rnum, rnum + 1));
// alert('rnum', rnum, '--', rnum + 1);
disp = chars.substring(rnum, rnum + 8);
}
OK, so from the clarification in the comments above the requirement is to generate a string that contains two random "words", where each "word" has four characters selected at random from a predefined set of available characters.
Following is one way to do that:
var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
function getWord(numChars) {
var word = "",
i;
for (i = 0; i < numChars; i++)
word += chars.charAt(Math.floor(Math.random() * chars.length));
return word;
}
function getWords(numWords, numCharsPerWord) {
var words = [],
i;
for (i = 0; i < numWords; i++)
words.push(getWord(numCharsPerWord));
return words.join(" ");
}
console.log( getWords(2, 4) ); // "a8ak 1wp9"
console.log( getWords(3, 4) ); // "7ua1 zh80 yy3r"
console.log( getWords(2, 5) ); // "j5ms2 e4xn8"
Demo: http://jsfiddle.net/dgnwh/

Categories

Resources