¿Alguien sabe cómo ordenar números en una matriz sin repetición?
Tengo una situación para generar una matriz de números como en el ejemplo a continuación:
// some function to generate this array of numbers function genNumbers() { // ...code to generate numbers and final return return [1,1,8,2,5,9,1,3,3,4] // return this array of numbers }Los números generados están bien, pero necesito estos números en orden no repetido como este:
[1,8,1,2,5,9,1,3,4,3] // all numbers from generated function but in different order.La matriz contiene más el mismo número como 1 y 3 de la muestra, pero no uno tras otro.
¡Gracias!
Uno de los comentaristas sugirió un buen enfoque: elija al azar, simplemente no elija el último que eligió. A nivel de contorno...
function arrayWithNoRepeat(length) { const result = []; for (let i=0; i<length; i++) { let lastValue = i ? result[i-1] : null; result.push(randomButNot(lastValue)); } return result; } ¿Cómo construir randomButNot() ? Aquí hay un par de alternativas:
Para un rango pequeño, cree el conjunto de valores seleccionables y elija uno...
// the range of this function is ints 0-9 (except anInt) function randomButNot(anInt) { const inBoundsValues = [0,1,2,4,5,6,7,8,9].filter(n => n!==anInt); const randomIndex = Math.floor(Math.random()*inBoundsValues.length); return inBoundsValues[randomIndex]; }Para una gama amplia, una idea es elegir un bucle que proteja contra el duplicado...
// the range is 0-Number.MAX_SAFE_INTEGER (except anInt) function randomButNot(anInt) { const choose = () => Math.floor(Math.random()*Number.MAX_SAFE_INTEGER) let choice = choose(); // we'd have to be very unlucky for this loop to run even once while (choice === anInt) choice = choose(); return choice; }Hay una discusión más larga sobre otras alternativas relacionadas con el tamaño del rango, la velocidad, el determinismo y la uniformidad de la distribución, pero se lo dejo a otros más inteligentes que yo.
Prueba esto,
function genNumbers() { // ...code to generate numbers and final return // let random = Array.from({ length: 10 }, () => Math.floor(Math.random() * 40)); //use this to generate random numbers let random = [5, 3, 6, 8, 1, 2, 2, 4, 9, 1]; // use this to generate fixed numbers let randomSorted = random.sort((a, b) => { return a - b; }) // sort the numbers let filterSame = randomSorted.filter((item, index) => { return randomSorted[index + 1] !== item; }) // filter the same numbers return filterSame // return the final result } console.log(genNumbers());