Skip to content

Instantly share code, notes, and snippets.

@rasmusbergpalm
Created November 25, 2013 12:47
Show Gist options
  • Save rasmusbergpalm/7640735 to your computer and use it in GitHub Desktop.
Save rasmusbergpalm/7640735 to your computer and use it in GitHub Desktop.
simple greedy algo for distributing integers (a) in a fixed set of buckets (N) such that the sum of content of the buckets are more or less equal.
def a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
def N = 3;
def buckets = [];
for (int i = 0; i < N; i++) {
buckets[i] = [k: [], t: 0]
}
a.sort { -it }.each { i ->
def b = buckets[0]
b.k.push(i)
b.t += i
buckets[0] = b;
buckets.sort { it.t }
}
println(buckets)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment