Gdscript: function to generate array of numbers that sum up to inputed number

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Titox

I know this seems silly but I need to create a function generate_sum_array(seed,factor) that will create an array of any number of elements arranged in random order in which all the array elements sum up to seed and have each have element is divisible by factor
For example:
generate_sum_array(100.10)
should return something like
[20,10,40,10,20] or [10,10,10,10,10,10,10,10,10,10] or [50,20,10,30,] etc. as long as the sum of all the elements is 100 the seed
There can be unlimited possibilities (I think…I am not really sure…How many different arrays can be generated)

Sounds like one hell of a question, don’t know the answer but,
you have a finite possibilities because you want all of them to have the same factor,
so the biggest array you can output will be equal to seed/factor and have that same value as well…
just out of curiosity why do you need it for? and try asking a mathematician friend if you got one

rustyStriker | 2019-12-09 20:03

I did this function for you. It may be slow to find a correct array of numbers on some occasions

# This function returns an array of numbers whose sum is equal to "Seed"
# and these numbers are divisible by "Factor"
# "Factor" must be greater than 0, smaller than "Seed"
# and "Seed" must be divisible by "Factor"
func generate_sum_array(_seed : int, _factor : int, _min_size : int = 0) -> Array:
	if _factor <= 0 || _factor > _seed || _seed % _seed != 0:  return []
	var correct_values = [1, _factor]
	# Get correct values
	for i in range(_factor, _seed):
		if i == 1 || i == _factor: continue
		if i % _factor == 0: correct_values.append(i)
	# get any array of numbers whose sum = _seed:
	var result = ""
	var sum = 0
	while result.length() == 0:
		while sum < _seed:
			randomize()
			var i = randi() % correct_values.size()
			sum += correct_values[i]
			result += "%s" % correct_values[i] if result == "" else ",%s" % correct_values[i]
			if sum > _seed:
				sum -= correct_values[i]
				for n in correct_values:
					if n == correct_values[i]: continue
					if sum + n == _seed:
						result += "%s" % n if result == "" else ",%s" % n
						break
				result = ""
				sum = 0
				break
		if _min_size != 0 && _min_size > result.split(",").size():
			result = ""
	
	return Array(result.split(","))

newold | 2019-12-09 23:37

:bust_in_silhouette: Reply From: tastyshrimp

This seems like a very general programming question and not really a GdScript one. As such, you can find implementations close to what you want, just need little tweak, in different forums. From a quick google search I can see this pseudo/java solution which seems would solve your problem.