Created
October 21, 2014 18:34
-
-
Save raidzero/9b8c030f1839e1879fd2 to your computer and use it in GitHub Desktop.
Split X into N uniformly-distributed pieces (java)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Random; | |
import java.lang.Math; | |
public class Split { | |
private static Random rand = new Random(); | |
public static void main(String[] args) { | |
ArrayList<Integer> list = splitNum(Integer.valueOf(args[0]), Integer.valueOf(args[1])); | |
System.out.println("sum: " + sumList(list)); | |
printList(list); | |
} | |
private static ArrayList<Integer> splitNum(int n, int numPieces) { | |
ArrayList<Integer> rtn = new ArrayList<Integer>(); | |
int mid = n / numPieces; | |
int delta = 0; | |
for (int i = 0; i < numPieces; i++) { | |
if (i % 2 == 0) { | |
delta = randInt(0, mid); | |
} else { | |
delta = -delta; | |
} | |
if (numPieces % 2 != 0 && i == numPieces - 1) { | |
delta = 0; | |
} | |
rtn.add(mid + delta); | |
} | |
int sum = sumList(rtn); | |
int diff; | |
if (sum > n) { | |
diff = n - sum; | |
} else { | |
diff = sum - n; | |
} | |
if (diff != 0) { | |
for (int i = 0; i < Math.abs(diff); i++) { | |
int index = randInt(0, numPieces - 1); | |
if (diff > 0) { | |
rtn.set(index, rtn.get(index) - 1); | |
} else { | |
rtn.set(index, rtn.get(index) + 1); | |
} | |
} | |
} | |
return rtn; | |
} | |
private static int randInt(int min, int max) { | |
return rand.nextInt((max - min) + 1) + min; | |
} | |
private static int sumList(ArrayList<Integer> list) { | |
int rtn = 0; | |
for (int n : list) { | |
rtn += n; | |
} | |
return rtn; | |
} | |
private static void printList(ArrayList<Integer> list) { | |
System.out.print("["); | |
for (int i = 0; i < list.size(); i++) | |
{ | |
System.out.print(list.get(i)); | |
if (i != list.size() - 1) { | |
System.out.print(", "); | |
} | |
} | |
System.out.println("]"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment