Vorausgesetzt, dass Sie ein Student sind, und das riecht wie Hausaufgaben, werde ich Ihnen zeigen eine stark kommentierte Version ich es in einer anderen Sprache (Rubin) implementiert und lassen Sie es in Java übersetzen für sich.
# Method to populate an array with values that sum to 3 * the array length
def populate(array)
total = 3 * array.length # determine the value to sum to
# the following allocates a temporary array with one more element
# than the input array, and populates it with random integers
# between zero and total, inclusive
tmp = Array.new(array.length + 1) { rand(total + 1) }
# replace the first entry with zero, the last with total.
# in reality, any two entries could be used, but values of
# zero and total are critical to the algorithm
tmp[0] = 0
tmp[-1] = total
# sort the temp array into ascending order
tmp.sort!
# since the smallest entry in tmp is zero, and the largest is total,
# and the array is in ascending order, successive differences between
# tmp entries will sum to total
array.each_index { |i| array[i] = tmp[i + 1] - tmp[i] }
# return the resulting array
return array
end
Wenn er gestartet wird, erzeugt diese Ergebnisse wie
[0, 0, 4, 8]
[3, 4, 0, 5]
[2, 1, 6, 3]
usw.
Der zugrunde liegende Algorithmus — n+1
Werte, die aus 0, total
und n-1
Zufallswerte im Bereich erzeugen [0 , total
], sortieren und finden die n
aufeinanderfolgenden Unterschiede — ist einfach in jeder Sprache zu implementieren e.
Sie müssen [ask] lesen – Amit
Willst du sagen, dass die Summe der Zellen gleich der ganzen Zahl sein muss? Weil du das nie gesagt hast. – pjs