I have a list of 4 activity choices
Activities
Activity 1
Activity 2
Activity 3
Activity 4
And I have a list of people who have chosen 4 activities ranked in order e.g.
Person Choices (1st,2nd,3rd,4th)
Person 1 2,3,1,4
Person 2 3,1,4,2
...
I am trying to allocate costs to the ranked choices based on their position and was just wondering how I could do it. An example is Person 1, whose 1st choice is activity 2 and the cost for this is 1. Their 2nd choice is activity 3 and the cost is 2 because it is in position 2 and so on. I am adding these costs to a lists because I need this cost list later in its same order.
Code I've tried
List<Integer> cost = new ArrayList<Integer>();
for(Person p: people){
for (int i = 0; i < p.getChoices().size(); i++) {
cost.add(p.getChoices(i+1);
}
}
Just some extra context The cost list will then be used to populate a transportation problem grid, where the sources are represented by the activity as seen below. The sources in the grid are in fixed positions, so when looking at person 1. Activity 2 was their 1st choice, Activity 3 their 2nd, Activity 1 their 3rd and Activity 4 their 4th.
Person 1 | Person2 | Person n
1 3 2
2 1 4
3 2 1
4 4 3
I keep getting confused on how to apply this as it should be simple. In my previous implementations I end up with just a cost list of 1,2,3,4 continuously. I cannot wrap my head around the theory for some reason (probs because its 5am XD). I am open to any theory or pseudocode. Thank you in advance!
If the cost of an activity for a person is its position in the choices, you can declare a method costOf
in class Person:
public class Person {
private final List<Integer> choices = new ArrayList<>();
public Person(Integer... choices) {
this.choices.addAll(Arrays.asList(choices));
}
public List<Integer> getChoices() {
return choices;
}
public int costOf(Integer activity) {
return choices.indexOf(activity)+1;
}
}
To print the grid, you would do that:
List<Person> persons = Arrays.asList(
new Person(2,3,1,4),
new Person(3,1,4,1)
);
// Print grid
for (int activity = 1; activity <= 4; ++activity) {
System.out.print(activity);
for (Person p: persons) {
System.out.print(" ");
System.out.print(p.costOf(activity));
}
System.out.println();
}
This will print:
1 3 2
2 1 0
3 2 1
4 4 3
You can see that there is a zero because the second person has no 2 in its choices.
Assuming it's a typo, and you replace the second 1 with 2, you get:
1 3 2
2 1 4
3 2 1
4 4 3
What was expected.