/**
* Glen's solution for this. Not sure whether it is 100% correct.
* It's for the seating problems.
*/
public class ChangingSeats {
public int getDistance(String s) {
boolean[] seats = new boolean[s.length()];
float people = 0;
for (int i = 0; i < s.length(); i++) {
seats[i] = s.charAt(i) == 'X';
if (seats[i])
people++;
}
// Find the "centre of gravity" of the people - moves will be made toward that
float seatMass = 0;
for (int i = 0; i < seats.length; i++)
if (seats[i])
seatMass += i;
// Find the "centre" position
int centre = (int) Math.round(seatMass / people);
// The answer is the total gaps between each person and the centre
int totalMoves = 0;
for (int i = 0; i < seats.length; i++)
if (seats[i]) {
// Add the total gaps between i and centre
if (i < centre) {
for (int j = i + 1; j <= centre; j++)
if (!seats[j])
totalMoves++;
} else if (i > centre) {
for (int j = centre + 1; j < i; j++)
if (!seats[j])
totalMoves++;
}
}
return totalMoves;
}
private static boolean test(String string, int expected) {
int actual = new ChangingSeats().getDistance(string);
if (actual == expected) {
System.out.println("Result correct for '" + string + "' = " + actual);
return true;
}
System.out.println("Incorrect result for '" + string + "'. Expected " + expected + ", but was " + actual);
return false;
boolean ok = true;
ok &= test("X.X", 1);
ok &= test("X.X.XXX", 3);
ok &= test("....X.X.X.X.XXXXX", 10);
ok &= test(".XXXXX..........X.X.XX......X.XX....", 81);
ok &= test("....................", 0);
ok &= test("........X............", 0);
ok &= test("X", 0);
if (ok)
System.out.println("All tests passed");
}
}