-5

I need to generate the unique numbers, join it with the letter and push to array.

arr = []
for (var i = 0; i < 5; i++) {
  function generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }
  var randomNum = generateRandomNumber(1, 15);
  if (!arr.includes(randomNum)) {
    arr.push('B' + randomNum.toString())
  } else {
    if (arr.length < 5) {
      return generateRandomNumber(min, max)
    } else break
  }
}

I have provisioned uniqueness check, however the same values are still coming.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Nikita
  • 3
  • 2
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Feb 10 '23 at 08:19
  • `if (!arr.includes(randomNum)) { arr.push('B' + randomNum.toString()) }` -- `arr.includes()` always returns `false` because you never push numbers to `arr`. It contains only strings that start with letter `'B'`. – axiac Feb 10 '23 at 08:20
  • `if (arr.length < 5)` -- this always happens in the provided code. The `for` loop runs at most five times, there is no way to get more than 5 items in `arr`. – axiac Feb 10 '23 at 08:23
  • `return generateRandomNmber(min, max)` -- this does not compile. The error is _"SyntaxError: return not in function"_. If, in the real code, the posted fragment is the body of a function then either make it compile or post it (the relevant code fragment) as a function. – axiac Feb 10 '23 at 08:26
  • The purpose of the code is not clear. Do you want to generate 5 random numbers and keep only the unique values or do you want to generate 5 unique random numbers? – axiac Feb 10 '23 at 08:29

2 Answers2

1

I have provisioned uniqueness check, however the same values are still coming.

The uniqueness check is incorrect.
The array contains only strings starting with letter 'B' (added by the line arr.push('B' + randomNum.toString())) while the uniqueness check searches for numbers.

The call arr.includes(randomNum) always returns false. Each and every generated value of randomNum is prefixed with 'B' and pushed into the array, no matter what the array contains.


Try a simpler approach: generate numbers, add them to the list if they are not already there, stop when the list is large enough (five items).
Then run through the list and add the 'B' prefix to each item.

Like this:

function generateRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}


// Generate 5 unique random numbers between 1 and 15
let arr = []
while (arr.length < 5) {
  let num = generateRandomNumber(1, 15);
  // Ignore a value that has already been generated
  if (!arr.includes(num)) {
    arr.push(num);
  }
}

// Add the 'B' prefix to the generated numbers
arr = arr.map((num) => `B${num}`);

console.log(arr);
axiac
  • 68,258
  • 9
  • 99
  • 134
  • Where is the answer to the question _"Why not unique numbers are still coming?"_ The question isn't how to write the code, but why doesn't this code work. – jabaa Feb 10 '23 at 08:44
  • The answer to that question is in [my first comment](https://stackoverflow.com/questions/75408479/why-not-unique-numbers-are-still-coming/75408631?noredirect=1#comment133056045_75408479). The code that tests for uniqueness (`if(!arr.includes(randomNum))`) is flawed and cannot detect the duplicates. This answer suggests a different approach that is easier to read and understand and less prone to contain hidden errors. – axiac Feb 10 '23 at 08:47
  • The answer to the question should be in your answer, not in a comment somewhere else. An alternative approach could be in a comment, and isn't required in the answer. – jabaa Feb 10 '23 at 09:00
  • The answer to the question is in my answer. I cannot see _your_ answer. – axiac Feb 10 '23 at 09:13
  • Yes, you edited your answer after my comment and then I upvoted your answer. Before my first comment, your answer didn't contain an answer. – jabaa Feb 10 '23 at 09:54
  • Whatever. I prefer to teach people how to do the things right and simple, not to help them succeed in their convoluted way of thinking. I showed in comments several things that are incorrect or too complicated in the OP's code. Do you want the real answer to the question? It does not work because it is bad code. Do not fix it, rewrite it. – axiac Feb 10 '23 at 10:28
  • Stack Overflow isn't a code writing service. It's a question and answer platform. The "what is the problem" is much more helpful than "my code is better" and this teaches how to avoid the same issue in the future. Yes, the code maybe bad, but this information isn't helpful for beginners. Explain, why this code is bad. What's the difference to your code? Not in a comment. In the actual answer. – jabaa Feb 10 '23 at 10:43
1

Condition only checked once in the loop. Also if the condition is in the else state, there is a chance that there will also be same number as previous. You can use this approach

let arr = []
function generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function add(){
  var randomNum = generateRandomNumber(1, 15);
    if(arr.length < 5){
        if (!arr.includes('B' + randomNum.toString())) {
            arr.push('B' + randomNum.toString())
        }
        add()
    }
  
}
add()
console.log(arr)
Kiyoshi
  • 56
  • 6
  • Why recursive function calls when a simple loop can do the same thing? – axiac Feb 10 '23 at 08:55
  • @axiac What if in the second cycle the random number is the same as the previous one? And if 3 cycle also ? Will you write for this condition as well? – Kiyoshi Feb 10 '23 at 09:01
  • What does a recursive call and cannot do a loop in this case? – axiac Feb 10 '23 at 09:12
  • You can use while as in your answer,but i don't think **for loop** is good one for this case.My approach, like yours, is just one example of how this can be implemented) – Kiyoshi Feb 10 '23 at 11:06