The approach is to sort the people using each of the six sorting methods described. If the sort
matches the input, then that method may have been used. Just for check zero, or more than one possible
solutions.

The Person class simply stores the age, weight, and name together; and allows us to create a Comparator
to sort them.

The PersonComparator class provides the compare() method for comparing two Person objects. The
PersonComparator constructor takes a String which determines the sorting method that it will use. This
happens in the switch statement inside the compare() method. Each of the cases of the switch statement
are the same, except that the order of the comparisons varies.

Be extra careful here to make sure that the items are getting sorted in the proper order. We can
String.compare() and Integer.compare() for the name and age. However, since we want to sort weight
in descending order, we need to multiple the result of the compare by -1 first before returning.

The sortType() method just creates an array of Person objects using the given input arrays, and then calls
testSortingMethod() for each method, keep tracking of valid sorting methods along the way.

In the testSortingMethod() method, we make a copy of the original array, and then sort it using the
given method. After it's sorted, we compare the copy to the original. Be sure to use
Arrays.equals() to test to see if the two arrays contain the same elements in the same order.
array1.equals(array2) will not work.

There was a lot of typing in this solution, but none of it was particularly hard. Just be careful in
the compare() method and it'll work out.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

We can create a legal arrangmenet if two conditions are met. First the number of boys must equals the number
of girls. Second, the number of both must be divisible by two. Since we've already checked that they're equal,
we only need to test one. These two conditions become pretty clear if you draw the solution out on a piece of paper.

We'll start by separating the boys from the girst. We can use Java's String.split() method to get the name
and gender of each attendee. The espression split("\\s+") just splits on the next whitespace. Then we
assign them to the correct Queue. A PriorityQueue was choosen it because it automatically keeps the entries
in a sorted order. We'll get the names in the order we need them practically for free.

Next, we check to see that the two conditions are met. If so, we can proceed to building the result. The
result String[] will have a length 2 larger than the input - in order to hold the HOST and HOSTESS. Position
0 gets the host, and length / 2 gets the HOSTESS. Then it's just a matter of alternating between pulling
the next girl and then boy off their respective queues until the result array is full.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

We can solve this easily in two steps. First, loop through all the Strings in textIn and make note
of the longest. Then loop through each of the Strings again, and pad them with spaces at the
beginning until their length matches the longest found in the first step.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

Monday, January 26, 2015

Determine the fewest number of swaps necessary to re-order a set of billiard
balls into a legal racking.

Java Source:

import java.util.PriorityQueue;
public class Pool {
private enum BallType {SOLID, STRIPE, EIGHT}
private static BallType[][] legalRacks = {{
BallType.STRIPE,
BallType.SOLID, BallType.SOLID,
BallType.STRIPE, BallType.EIGHT, BallType.STRIPE,
BallType.SOLID, BallType.STRIPE, BallType.SOLID, BallType.STRIPE,
BallType.STRIPE, BallType.SOLID, BallType.STRIPE, BallType.SOLID,
BallType.SOLID
}, {
BallType.SOLID,
BallType.STRIPE, BallType.STRIPE,
BallType.SOLID, BallType.EIGHT, BallType.SOLID,
BallType.STRIPE, BallType.SOLID, BallType.STRIPE, BallType.SOLID,
BallType.SOLID, BallType.STRIPE, BallType.SOLID, BallType.STRIPE,
BallType.STRIPE
}};
/*
* Represents a configuration of balls, and how many moves it took to
* get there. Includes some methods for swapping balls, and determining
* how far away it is from a legal rack.
*/
private class SearchNode implements Comparable {
private BallType[] rack;
private final int moves;
private int numOutOfPlace = -1;
SearchNode(BallType[] rack, int moves) {
// Make a defensive copy of the rack that was passed in.
this.rack = new BallType[rack.length];
System.arraycopy(rack, 0, this.rack, 0, rack.length);
this.moves = moves;
}
/*
* Returns the number of balls that are out of place. Since there
* are more than one legal racks, it checks them all, and returns
* the minimum. Note, this calculation is only done once.
*/
int getNumOutOfPlace() {
if (numOutOfPlace >= 0) {
return numOutOfPlace;
}
numOutOfPlace = Integer.MAX_VALUE;
// Check each legal configuration.
for (int i = 0; i < legalRacks.length; i++) {
int n = 0;
for (int b = 0; b < rack.length; b++) {
if (rack[b] != legalRacks[i][b]) {
n++;
}
}
numOutOfPlace = Math.min(numOutOfPlace, n);
}
return numOutOfPlace;
}
/*
* A heuristic representing how ideal this state is. It is better
* to have less balls out of place in a lower number of moves.
*/
int getPriority() {
return getNumOutOfPlace() + moves;
}
/*
* Returns a new SearchNode with one pair of balls swapped. Number
* of moves is incremented by one. If the 8 ball is out of position,
* it will be swapped into the correct place first.
*/
SearchNode swapBalls(BallType[] legalRack) {
int ball1;
int ball2;
SearchNode newNode = new SearchNode(rack, moves + 1);
// If the 8 ball is out of place, fix that first.
if (rack[4] != BallType.EIGHT) {
ball1 = 4;
ball2 = 0;
while (rack[ball2] != BallType.EIGHT) ball2++; // Find the 8.
} else {
/*
* ball1 is the first ball that is out of place - regardless
* of it's type (solid / stripe).
* ball2 is the first ball out of place of the type that
* should be at the location of ball1.
*/
ball1 = getFirstOutOfPlace(legalRack, null);
ball2 = getFirstOutOfPlace(legalRack, legalRack[ball1]);
}
newNode.rack[ball1] = rack[ball2];
newNode.rack[ball2] = rack[ball1];
return newNode;
}
/*
* Find the first ball that does not match the corresponding legal
* rack. If type is null, it can be either stripe or solid. If
* type is given, then the out of place ball must be of that type.
*/
private int getFirstOutOfPlace(BallType[] legalRack, BallType type) {
for (int i = 0; i < rack.length; i++) {
if ((type == null) || (rack[i] == type)) {
if (rack[i] != legalRack[i]) {
return i;
}
}
}
return -1;
}
// Sort SearchNodes based on their priority.
public int compareTo(SearchNode o) {
return Integer.compare(this.getPriority(), o.getPriority());
}
}
public int rackMoves(int[] triangle) {
/*
* Using a PriorityQueue to process the possible solutions will allow
* us to focus on the most promising paths first. That is those closest
* to a legal rack in the fewest number of moves.
*/
PriorityQueue possibleSolutions = new PriorityQueue<>();
/*
* Convert the given input array into an array of BallType objects.
* These will be easier to work with then constantly having to check
* ranges to determine if the ball is a stripe or solid.
*/
BallType[] rack = new BallType[triangle.length];
for (int i = 0; i < triangle.length; i++) {
if (triangle[i] < 8) rack[i] = BallType.SOLID;
else if (triangle[i] > 8) rack[i] = BallType.STRIPE;
else rack[i] = BallType.EIGHT;
}
// Put our starting position into the PriorityQueue
SearchNode n = new SearchNode(rack, 0);
possibleSolutions.add(n);
// The fewest moves seen so far that leads to a legal rack.
int minNumberOfMoves = Integer.MAX_VALUE;
while (true) {
if (possibleSolutions.isEmpty()) {
return minNumberOfMoves;
}
// Get the most promising node.
SearchNode s = possibleSolutions.poll();
/*
* If there are no balls out of place, check to see if this
* is the best solution found so far.
*/
if (s.getNumOutOfPlace() == 0) {
minNumberOfMoves = Math.min(minNumberOfMoves, s.moves);
} else {
/*
* Make sure the move that we're about to make keeps us below
* the number of moves in the best solution. Otherwise, there's
* no point in trying it.
*/
if ((s.moves + 1) < minNumberOfMoves) {
for (int i = 0; i < legalRacks.length; i++) {
/*
* Add to possible solutions swappings that will
* get us closer to each of the legal racks.
*/
possibleSolutions.add(s.swapBalls(legalRacks[i]));
}
}
}
}
}
}

Notes:

The first thing I did was to create an enumerated type to represent the three types of billiard
balls: Solid, Stripe, and 8-ball. It seemed easier to work with just these three and avoid
having to deal with the individual values of the balls. With that, I created an array of
legal rack configurations. Note that the legal racks are inverses of each other. Looking
back, I probably could have made better use of that fact.

Next, I define an inner class called SearchNode. This holds a rack configuration, the number
of moves required to reach this state, and some code to count the number of balls that are out
of place, and to swap balls - leading to a new configuration. The method getPriority() gives
us an idea of how good the current state is. The fewer balls out of place, and the less
moves needed to reach this state, the better.

The swapBalls() method first looks to see if the 8 ball is in position 4. If it's not, then we'll
swap the ball in position 4 with the 8 ball. Otherwise, we look for the first ball that is
out of position (i.e. a Stripe where a Solid belongs). Then we look for an opposing ball
to swap with that.

Finally, the SearchNode class provides a compareTo() method. The algorithm uses a priority
queue to examine the SearchNode with the lowest priority. The compareTo() method allows
SearchNodes to be sorted.

The heart of the algorithm is in the while loop of the rackMoves() method. It's based on
the A* algorithm. We start by placing the initial state into the priority queue. Then
we remove the lowest priority state from the queue and add two new states representing
steps toward one of the two legal end states.

Once we've found a state that is legal, we update minNumberOfMoves. Any state that cannot
reach the end state in less moves will not be added to the priority queue, and that line of
progression will terminate.

Once the queue is empty, we'll have found our minimum possible number of moves.

This solution is probably overkill given the problem. With only 15 balls, and noting
that each swap (not including the 8 ball) brings two more balls into alignment, it shouldn't
be hard to write a brute-force approach. I like this solution becase it is more general.
It can be expanded to take any starting condition and find the best sequence to get
to any ending state. The same algorithm can be used to solve a rubik's cude, those sliding
tile games, or a host of other problems.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

We say that two calendars are the same if the meet the following conditions:

Any date falls on the same day of the week. (i.e. Jan 1 is a Sunday for both years). and

Both years have the same leap year status. Either both are, or both aren't leap years.

The first thing useAgain() does is store the leap year status of the current year. We'll need this
later to check that it matches the status of the candidate year.

Next, we set dayOfWeek to it's initial value. Note that we don't care what day this represents. It
could be Sunday, Monday, etc. The only thing that matters is that we return to this value.

Finally, it's just a matter of adding 365 (+1 if it's a leap year), mod'ing that by 7 and seeing if
we're back to the starting day. If so, and the leap year status matches, we've found our answer.

The logic for isLeapYear() is taken directly from the problem description. First check to see if
the year is divisible by 4. If so, then check to see if it's not divisible by 100, unless it is
also divisible by 400.

I've provided an alternate solution in useAgain1() that makes use of Java's GregorianCalendar.

Here, we create a new GregorianCalenar for January 1st of the given year (any date could have been chosen),
and remember its day of the week. Then we keep adding a year and checking the day of the week and leap year
status just as before.

An interesting note about GregorianCalendar - it provides an instance method isLeapYear(int year). A better
way would be to create a static method GregorianCalendar.isLeapYear(int year) that could give the result for
any year; and also provide an instnace method isLeapYear() with no parameters that gives the status of the
current object. With the chosen implementation, you must create an instance of the GregorianCalendar to
get the leap year status of some year that may be unrelated to that object. The second half of useAgain2()'s if
statement could be much cleaner as:

GregorianCalendar.isLeapYear(year) == c.isLeapYear()

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

This is a simple problem that can be solved in less time that it takes to read the description.

We'll use the variable p to keep track of the inchworm's current position. This starts at zero, and get
incremented by rest until the inchworm goes beyond the end of the branch.

At each position, we'll check to see if there's a leaf there, and if so, increment the number of meals eaten. We can tell
if there is a leaf at the current position by using the % operator. If position is evenly divided by leaf, then we've stopped
on a leaf.

Once p is greater than branch we can return the value in meals.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

The solution uses recursion to draw all of the inner squares, and then completes the outer square. The draw() method
simply initializes a new 2-dimensional char array and then calls drawSquare(). When drawSquare() completes, it just
converstion the char[][] back to a String[] and returns it. The call to drawSquare() passes the char[][] and the index
0, which indicates the top-left corner of the outermost square.

The drawSquare() method handles all the work on turning on the appropriate locations. It is passed the top-left corner
of the current square, and uses that and the size of the char[][] to determine the location of the bottom-right corner.
If these values are not the same, recursively call drawSquare moving the top-left corner in and down by 2.

As the recursion unwinds, we have a loop to draw each of the sides. Note the index representing the top edge will always
equal the index of the left edge. So one variable (topOrLeft) will suffice. Similarly, the index for the bottom edge
will be the same as the index of the right edge - thus bottomOrRight.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

The current state can be described fully with the following variables:

A set of passengers waiting to be picked up.

A set of passengers currently in the elevator.

The floor the elevator is currently on.

How much time has elapsed.

At any point, the elevator can either move to pick someone up, or move to drop
them off. This solution uses recursion to try every possible combination.

The timeWaiting() method just initializes the simulations with an empty elevator,
everyone in the waiting Set, and the elevator on floor 1 at time 0.

In moveElevator() we first check to see if we're done - that is, the elevator is
empty and nobody is waiting to be picked up. If that's the case, then we'll
update minFinishTime to the smaller of it's current value and our current time.

If we're not done, then we'll recursively call moveElevator with every possible
combination of picking up or dropping off a passenger.

To simulate picking up a passenger, we create a newWaiting set that contains all
the members of the current waiting set, except for the person that we're picking up.
We then create a newElevator set using the contents of the current elevator set and add
the new passenger. The travel time is calculated between floors, and our newTime
becomes the greater of the time when the elevator arrives, and the arrival time
for that person. moveElevator() is then recursively callled with the new parameters.

Similarly, to drop someone off, we create a newElevator set that contains everyone from
the current elevator set except the person that we dropped off. There is no need
to create a newWaiting set, since that will not have changed. Again, the times
are calculated moveElevator() gets called recursively.

When all of the scenarios have completed, minFinishTime will contain the shortest
time in which all passengers can be serviced, so we just return that.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

The tricky part of this problem is determining where each cluster starts and ends. I've created the methods findClusterStart()
and findClusterEnd() to take care of that. With those indexes known, we simply count the number of knots between those points. The
knots are read from left to right, and for each cluster, the current value is multiplied by 10, and the number of knots in the
current cluster is added.

findClusterStart() returns the index of the first 'X' found at or after p among any of the knots given in the input array. The return
value will be at most ropeLength.

findClusterEnd() is very similar to findClusterStart(). Here we're looking for the greatest index. It starts at position p, and increments
the index so long as the current character is an 'X'. This is done for each knot in the knots array, and the greatest index is returned.

doCount() just returns the number of 'X's found in a string between the start and end indexes.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

This is a pretty straight forward problem. Just follow the instructions carefully, and you shouldn't run into any problems.

To implement the stack, I chose to extend java.util.Stack and override the pop() and push() methods. Although the problem doesn't
explicitly state it, you can see from the first example that if pop() is called on an empty stack, it should return 0. The
default behavior of java.util.Stack is to throw an EmptyStackException. I also modified push() to check that the value is
between MIN_STACK_VAL (-1000000000) and MAX_STACK_VAL (1000000000) before pushing it. If the value is outside these bounds,
it will throw an IllegalArgumentException.

When the ',' command is encountered, a value is popped from the stack and appended to output. This is the only time that
output is modified. Whenever output changes, we check to see if it now equals source, or failing that, ensure source continues
to begin with output.

Since output is only changed by the ',' command, if '@' is ever encountered, we return BADEND. At that point
output cannot match the program since we would have caught it when processing the ',' command.

The while loop watches the value of cycles (which gets incremented after each command is processed), and terminates
when it reaches MAX_CYCLES.

The only other exit point is when we catch an IllegalArgumentException from pushing a value outside the legal range onto
the stack. This exception is caught and returns an OVERFLOW message.

The rest of the program simply implements the logic given in the problem statement. Again, be careful and you won't have
any problems.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.

In order to be a happy letter, more than half the letters in the string must be that character. If the frequency
of a character is half (or less) the length of the input string, then other characters can be paired up
with the current character until all instances of the current character are eliminated. Conversely, if the frequency
is greater than half, then matching all other characters with the current character will be insufficient to eliminate all
of the current character.

The solution then is just to loop through all the characters in the input string. For each letter, count the
number of times it appears, and if that's greater than half the size of the input string, return it as the
happy letter. If no character meets that criteria, return '.'

Note that only one character can be a happy letter, because more than half the input string must consist of that character.
It's impossible for more than one character to take up more than half the string.

Thank you for taking the time to read this solution. I welcome
any feedback you may have.