So, recently I started a coding challenge to improve my coding skills. The context of the challenge is to find the right masses of a given List that sum up to a given weight of an animal. The function should return a List that includes all needed masses.
The given masses list includes the following elements: [1, 2, 4, 8, 16, 32, 64, 128]. The given weight is 145.
The code should also work for weights different to the given weight of 145.
Here is the code given by the challenge:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class Scale {
static List<Integer> getMasses(Integer weight, List<Integer> allMasses) {
// You need to implement this method.
// You can also add attributes to the class and add new methods or functions
throw new NotImplementedException();
}
}
Here is my current code:
class Scale {
static List<Integer> getMasses(Integer weight, List<Integer> allMasses) {
// You need to implement this method.
// You can also add attributes to the class and add new methods or functions
for(int i = 0; i < allMasses.size(); i++){
System.out.println(allMasses.get(i));
}
List<Integer> neededMasses = new ArrayList<Integer>();
for(int i = 1; i < allMasses.size() + 1; i++){
if(allMasses.get(allMasses.size() - i) == weight){
neededMasses.add(allMasses.get(allMasses.size() - i));
return neededMasses;
}
else if(allMasses.get(allMasses.size() - i) == 0){
return neededMasses;
}
else if(allMasses.get(allMasses.size() - i) > weight){
continue;
}
else{
weight = weight - allMasses.get(allMasses.size() - i);
neededMasses.add(allMasses.size() - i);
}
}
throw new NotImplementedException();
}
}
If I run my code now, the list that i should return includes [1, 4, 7]. But it should include [128, 16, 1].
Can someone help me to figure out how to get my code to work? Am I on the right track or is my code completly wrong?