mardi 2 juillet 2019

Generating m numbers that equal 100 but difference between two numbers have to be greater than 4

I'm trying to generate numbers that are equal 100(%) but all numbers have to be atleast 4 numbers from each other. So if I generate 4 numbers they have to be like this for example [22,28,15,35] and can't be like this [22,28,20,30] as difference between 28-30 and 22 - 20 is less than 4.

I was able to put together method for generating numbers that equal something which looks like this.

generate (max, many) {
    this.numbers_array = []
    this.normalized_numbers_array = []
    this.sum = 0 
    for (let i = 0; i < many; i++) {
      this.numbers_array.push(Math.random())
      this.sum += this.numbers_array[i]  
    }
    this.remaining = max
    for (let i = 0; i < this.numbers_array.length; i++) {
      this.outcome= (this.numbers_array[i] / this.sum) * max
      this.normalized_numbers_array[i] = Math.floor(this.outcome)
      this.remaining -= this.normalized_numbers_array[i]
      if (i + 1 == this.numbers_array.length) {
        while (this.remaining > 0) {
          this.normalized_numbers_array[i]++
          this.remaining--
        }
      }
    }
  }  

And works fine. My next approach was trying to compare the normalized numbers with each other through two for loops and if statements. Then according to the differences between the numbers with each other I wanted add 2% to one and substruct 2% from other of the two numbers that are being compared. Then I put them in new array which I wanted to normalized again.

   for (let i = 0; i < this.normalized_numbers_array.length; i++) {

  for (let j = i + 1; j < this.normalized_numbers_array.length; j++) {

    if (Math.abs(this.normalized_numbers_array[i] - this.normalized_numbers_array[j]) < 5) {
        //do something
      if (this.normalized_numbers_array[i] > this.normalized_numbers_array[j]) {
        //do something
      } else if (this.normalized_numbers_array[i] <= this.normalized_numbers_array[j]) {
    //do something  
      }
    }
}

}

This approach is flawed, though. As by adding or substructing I can make new differences that are less than 4. For example [35,18,26,21]->[35,16,26,23] Difference between 26 and 23 is 3 after the change.

My thought was to create another loop that would be going as long as there are differences. But I'm not sure that would work. So I was wondering whether there is better working solution for this problem- maybe being able to generate those numbers with differences in size from the start and not have to change them after.




Aucun commentaire:

Enregistrer un commentaire