You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them.
Given the lengths of sticks, print the number of sticks that are left before each iteration until there are none left.
For example, there are sticks of lengths . The shortest stick length is , so we cut that length from the longer two and discard the pieces of length . Now our lengths are . Again, the shortest stick is of length , so we cut that amount from the longer stick and discard those pieces. There is only one stick left, , so we discard that stick. Our lengths are .
Function Description
Complete the cutTheSticks function in the editor below. It should return an array of integers representing the number of sticks before each cut operation is performed.
cutTheSticks has the following parameter(s):
- arr: an array of integers representing the length of each stick
Using Java 8 for this solution:
import java.util.stream.Collectors;
static int[] cutTheSticks(int[] arr) {
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
List<Integer> result = new ArrayList<Integer>();
int counter = 0;
while (list.size() > 0) {
Collections.sort(list);
int min = list.get(0);
for (int i = 0; i < list.size(); i++) {
if (list.get(i) > 0 && list.get(i) - min >= 0) {
list.set(i, list.get(i) - min);
counter++;
}
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 0) {
list.remove(i);
}
}
if (!result.contains(counter)) {
result.add(counter);
}
counter = 0;
// System.out.println("l "+list);
}
for (int i = 0; i < result.size(); i++) {
if (result.get(i) == 0) {
result.remove(i);
}
}
int[] fRes = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
fRes[i] = result.get(i);
}
//System.out.println("r " + result);
return fRes;
}