lundi 2 novembre 2020

Sort and print number of occurences of random numbers

const randomNum = [];

for (let i = 0; i <= 20; i += 1) {
  randomNum.push(Math.floor(Math.random() * 20 + 1));
}

then

function getOccurrence(array, value) {
  return array.filter((x) => x === value).length;
}

My goal is to print out something along the line of

Number 1, 6, 12, 3, 9 occurred 1 times.
Number 2, 5, 7, 19, 17 occurred 2 times.
Number 15, 11 occurred 3 times. 

And so on.

Any idea how i should go about this?

I was thinking of making a function, something along the line of

function numberOccurrence(arr, arrLength){

}

So i in the future could feed it ANY array with with x amount of numbers in it, but I'm unsure how to go forward. I've tried multiple .includes, .indexOf, ifs and so forth, but i feel stuck, could anyone give me a push in the right direction?

I feel like having a loop which counts how many times 1 occurs, then saves that into an object like this

numObj = {
1: 2,
2: 1,
3: 4,
}

Where the object is built as soon as the function runs, and it builds it based on the arrLength parameter i feed the function in the beginning.

Anything is appreciated, thank you!

Update: I manage to SOMETIMES print part of the answer right with this:

function getOccurrence(array, value) {
  return array.filter((x) => x === value).length;
}

for (let i = 1; i <= randomNum.length; i += 1) {
  let numOccurr = [];
  for (let j = 1; j <= randomNum.length; j += 1) {
    if (randomNum.includes(j)) {
      if (getOccurrence(randomNum, j) === i) {
        numOccurr.push(j);
        if (j === randomNum.length) {
          printOut(`Number: ${numOccurr.join(', ')} occurrs ${i} times.`);
          numOccurr = [];
        }
      }
    }
  }
}

if i check my array after "Number: 20 occurred 4 times" gets printed, i see that the answer is correct, problem is, sometimes it prints every number generated 1 time, then sometimes only those generated 2 times, and so on. And sometimes nothing gets printed




Aucun commentaire:

Enregistrer un commentaire