I'm working on a loop that adds 10 unique random integers from 1-10 to an array, so the expected result would be 2,1,4,6,10,7,9,8,5,3
I manage to generate random numbers and only add the unique ones, my problem is, its not complete 10 items, I think the problem is upon checking I it doesn't generate again.
Hope you help me.
Thanks.
for (let i = 0; i < 10; i++) { var arrNum = []; setTimeout(function() { var r = Math.floor(Math.random() * 10) + 1; while (arrNum.includes(r) == false) { arrNum.push(r); } if (i == 9) { $('ul').append('<li>' + arrNum + '</li>'); } }, 500); }
ul li{ list-style-type: none; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul></ul>
while (arrNum.includes(r) == false) {
arrNum.push(r);
}
That adds the number as long as it doesnt exist, so it will only run once, and if the number exists already it doesnt generate a new one, you want:
const result = [];
for(let i = 1; i <= 10; i++) {
let random;
do {
random = 1 + Math.floor(Math.random() * 10);
} while(result.includes(random));
result.push(random);
}
But its probably way more easy to just shuffle an array with the numbers 1 to 10.
Your code has a mistake. The i
is not the ideal way to check for 10 occurrences as it is incremented even if variable r
does not satisfy your condition - arrNum.includes(r) == false
.
The check should be made by array length.
Replace if (i == 9)
with if(arrNum.length = 10)
in your code.
Create an array with numbers from 1 to N (first line). Replace N with 10 in your case. Then sort it randomly.
const numbers = [ ...Array(N).keys() ].map(o => o + 1);
numbers.sort(() => Math.random() - 0.5);
console.log(numbers); // [ 6, 4, 5, 2, 1, 9, 3, 7, 8, 10 ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.