mercredi 21 juillet 2021

How would you make a function that adds random numbers from a list to reach a certain value?

the question title might be a little bit confusing so let me see if I can explain it a little better here. I want to create a function that will generate a sequence of numbers (in any order or combination) that are in a pre-defined list to add to a certain value.

IE.

var x = [6, 4, 3]; //pre-defined values
var n = 24; //the number I want to add too

function myFunc(values, goal) {
    //code for algorithm
    //return a sequence of numbers from the list that add to 24
}

myFunc(x, n)

Example Outputs from myFunc:

  • 4, 4, 4, 6, 3, 3 --> 24
  • 6, 4, 3, 3, 4, 4 --> 24
  • 3, 4, 4, 6, 3, 4 --> 24
  • etc.

The algorithm would be able to return one of the many permutations that exist but I just came up with a couple for the sake of the question.

Responses don't have to be language-specific I just need a general idea/insight on how to create and structure this algorithm.

Thanks!




Aucun commentaire:

Enregistrer un commentaire