0

I need to generate array from letters A,H,O,J and numbers 0-9. I want to generate letters into new array in order AHOJ. The individual characters can appear elsewhere in new array but always in AHOJ order and they dont need to follow each other. Remaining indexes of new array will be filled with digits. Examples - A123H85O2J3, AHOJ9854273, 012AH851OJ3 and so on. The order of AHOJ must not be randomized within new array. I have this code, but is probably completly wrong. It only works as expected when condition equal to 7 is met.

let letters = ['A','H','O','J'];
let newArray =new Array(11);
let lastIndex = 10;

for (let i = 0; i < letters.length; i++) {
    
    newIndex = Math.floor(Math.random() * lastIndex);
    console.log(newIndex);
    if (newIndex == 7) {
        for (let j = 0; j < letters.length; j++) {

            newArray.splice(j + 7,1,letters[j]);
        }
        for ( let k = 0; k < 7; k++) {
            newArray.splice(k,1,Math.floor(Math.random() * 10).toString());
        }
        break;
    }
    else if (newIndex > 7) {
        lastIndex = Math.floor(Math.random() * 6);
        newArray.splice(lastIndex,1,letters[i]);
    }
    else {
        newArray.splice(newIndex,1,letters[i]);
        
    }



    
    console.log(letters[i]);
}

console.log(newArray);

2 Answers 2

2

It can be simplified to one loop :

let letters = ['A','H','O','J'];

for (let l = 5; l < 12; l++)    // for random indexes from 4 to 11
{
    let position = Math.floor(Math.random() * l);
    let digit = Math.floor(Math.random() * 10);
    letters.splice(position, 0, digit);
}

console.log( letters.join(''), letters.length );

Sign up to request clarification or add additional context in comments.

Comments

0

for (let i = 0; i < 100; i += 1) {
  console.log(generate('AHOJ', 11))
}

function generate(word, length) {
  // create array [0, 1, 2, ..., length - 1]
  const indexes = [...Array(length).keys()]
  // get unique random indexes for each character of the word
  const reserved = [...word].map(() => {
    // random index of indexes array
    const index = Math.floor(Math.random() * indexes.length)
    // remove the number at index from indexes array
    const res = indexes.splice(index, 1)
    // return removed number
    return res[0]
  })
  
  const result = []

  for (let i = 0, w = 0; i < length; i += 1) {
    // if index is reserved, push a letter from word
    if (reserved.includes(i)) {
      result.push(word[w])
      w += 1
    // push random digit otherwise
    } else {
      result.push(Math.floor(Math.random() * 9))
    }
  }
  
  return result.join('')
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.