0

Does anyone know how to order numbers in array with no repeat.

I have situation to generate array of numbers like in sample below:

// 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
}

Generated numbers is ok, but I need this numbers in non-repeat order like this:

[1,8,1,2,5,9,1,3,4,3] // all numbers from generated function but in different order.

Array contain more same number like 1 and 3 from sample but not one after the other.

Thank you!

Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30
Pooky
  • 27
  • 5
  • 2
    [How to reorder an Array to avoid consecutive duplicates](https://stackoverflow.com/questions/65053770/how-to-reorder-an-array-to-avoid-consecutive-duplicates) – isherwood Feb 24 '22 at 19:37
  • 5
    What if there's no possible order like this? For instance, if the array is `[1, 2, 1, 1]` – Barmar Feb 24 '22 at 19:37
  • Just count how many you have of each, and then pick and reduce count, go to next number... repeat. – trincot Feb 24 '22 at 19:40
  • If array [1,2,1,1] update only that index with another numbers from range (range from 1 to 10). – Pooky Feb 24 '22 at 19:45
  • 2
    So why don't you apply that strategy from the start? Just generate a first number, put it in the array, generate a second number, but require that it's different from the first, ...etc. – trincot Feb 24 '22 at 19:47
  • At start I generate each number from range 1 to 10 and add it to array, I put limit to generated number let's say generate 5 numbers from range 1 to 5. In most cases I get proper order but some times get repeated numbers :( – Pooky Feb 24 '22 at 19:50
  • The changed title was misleading (mentioned "sort") so I changed it back to the original one: "Random numbers in array with no sequential repeats" – Rickard Elimää Feb 24 '22 at 20:45
  • Does this answer your question? [How to reorder an Array to avoid consecutive duplicates](https://stackoverflow.com/questions/65053770/how-to-reorder-an-array-to-avoid-consecutive-duplicates) – kmoser Feb 24 '22 at 20:45

4 Answers4

1

One of the commenters suggested a good approach: pick randomly, just don't pick the last one you picked. At the outline level...

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;
}

How to build randomButNot()? Here are a couple alternatives:

For a small range, build the set of pick-able values and pick one...

// 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];
}

For a large range, one idea is to choose in a loop that guards against the duplicate...

// 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;
}

There's a longer discussion about other alternatives relating range size, speed, determinism and uniformity of distribution, but I'll leave it to others smarter than me.

danh
  • 62,181
  • 10
  • 95
  • 136
-1

Try this,

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());
Husnul Jahneer
  • 262
  • 2
  • 5
-1

You can use Set object. Mdn

let myList = [1,8,1,2,5,9,1,3,4,3]

let unique = [... new Set(myList)]

unique.sort((a,b)=> {return a-b})

console.log(unique)
-1

Actually I fix my problem in this way. If current number = previous repeat generate process until get array with proper order. Maybe not best way to fix this but it's fast enough.

Here is function:

function genNumbers() {
    let num = [];
    
    const generate = () => {
      for (let x = 0; x < 10; x++) {
        const _number = Math.floor(Math.random() * (10 - 1) + 1); 
        num.push(_number);

        // if current number === previous
        if (_number === num[x - 1]) {
          num = []; // empty array
          return generate(); // generate again (repeat process)
        }
      }
    };

    generate();

    return num
  }
  
  console.log(genNumbers())
Pooky
  • 27
  • 5