tag:blogger.com,1999:blog-45798746194281568542020-02-29T00:07:48.706-05:00Top Coding SolutionsA blog dedicated to helping you to become a better coder.Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.comBlogger142125tag:blogger.com,1999:blog-4579874619428156854.post-83188349379608607322015-11-22T10:33:00.001-05:002015-11-22T10:33:27.326-05:00SimpleCalculator<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=2272" target="_blank">TopCoder Problem Statement - SimpleCalculator</a> </td> </tr> <tr><td>Single Round Match 178 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Implement a simple calculator that can handle addition, subtraction, multiplications, and division. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class SimpleCalculator {<br /> 2<br /> 3 public int calculate(String input) {<br /> 4<br /> 5 String[] ints = input.split("[+\\-\\*\\/]");<br /> 6<br /> 7 char op = input.charAt(ints[0].length());<br /> 8<br /> 9 int i1 = Integer.parseInt(ints[0]);<br /> 10 int i2 = Integer.parseInt(ints[1]);<br /> 11<br /> 12 if ('+' == op) return i1 + i2;<br /> 13 if ('-' == op) return i1 - i2;<br /> 14 if ('*' == op) return i1 * i2;<br /> 15 return i1 / i2;<br /> 16<br /> 17 }<br /> 18<br /> 19 }<br /></pre> </div> <div class="header">Notes:</div> <p> The only tricky part here is parsing the input to obtain the two integers and the operand. We can use the regular expression on line 5 for this. This will look for any of the characters (+, -, *, or /) and split the input into the integer that comes before and after the operator. When constructing the regular expression, you'll need to use \\ to escape some of the characters. </p> <p> int[0] will hold the first number. Thus, we can obtain the operator buy using the length of int[0]. This is done on line 7. We can use Integer.parseInt() to get the integer values from the strings. </p> <p> Then it's a simple matter of checking the value of the operator and performing the correct operation. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-36746579684566027292015-10-20T15:52:00.003-04:002015-10-20T15:52:56.554-04:00BirthdayOdds<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1848" target="_blank">TopCoder Problem Statement - BirthdayOdds</a> </td> </tr> <tr><td>Single Round Match 174 Round 1 - Division I, Level One</td></tr> <tr><td>Single Round Match 174 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Calculate the mininum number of people required to assure that the probability of two people sharing a birthday meets the given threshold. The number of days in a year may vary. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1<br /> 2<br /> 3 public class BirthdayOdds {<br /> 4<br /> 5 public int minPeople(int minOdds, int daysInYear) {<br /> 6<br /> 7 double pA = 1.0;<br /> 8 double days = (double) daysInYear;<br /> 9 double cutOff = 1.0 - (minOdds / 100.0);<br /> 10<br /> 11 int numPeople = 1;<br /> 12<br /> 13 while (pA > cutOff) {<br /> 14 pA *= ((double) (daysInYear - numPeople) / days);<br /> 15 numPeople++;<br /> 16 }<br /> 17<br /> 18 return numPeople;<br /> 19<br /> 20 }<br /> 21 }</pre> </div> <div class="header">Notes:</div> <p> For a detailed discussion of the Birthday Problem, see the wikipedia entry <a href="https://en.wikipedia.org/wiki/Birthday_problem">here</a>. This solution is based on the formula given in the "Calculating the probability" section. </p> <p> Essentially we're calculating the probability that there is <strong>not</strong> a match, and then adding more and more people thus reducing that probability until a certain threshold is met. That threshold is (1 - minOdds) since we're calculating the probability of not matching whereas minOdds is the probability of a match. </p> <p> pA begins at 1 (i.e. daysInYear / daysInYear), then is multiplied by (daysInYear - 1 / daysInYear), (daysInYear - 2 / daysInYear), (daysInYear - 3 / daysInYear), ... With each multiplication pA gets smaller until it falls under the cutoff. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-90948411608161999742015-10-20T15:09:00.003-04:002015-10-20T15:09:52.319-04:00RGBColor<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=2251" target="_blank">TopCoder Problem Statement - RGBColor</a> </td> </tr> <tr><td>Single Round Match 176 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Compute the compliment of the given RGB color. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 import java.util.*;<br /> 2 import java.math.*;<br /> 3 import static java.lang.Math.*;<br /> 4<br /> 5 public class RGBColor {<br /> 6<br /> 7 private static final int RGB_MAX = 255;<br /> 8 private static final int GREY_TOLERANCE = 32;<br /> 9<br /> 10 public int[] getComplement(int[] rgb) {<br /> 11<br /> 12 int[] compliment = new int[rgb.length];<br /> 13<br /> 14 boolean isGrey = true;<br /> 15<br /> 16 for (int i = 0; i < rgb.length; i++) {<br /> 17 compliment[i] = RGB_MAX - rgb[i];<br /> 18 if (Math.abs(rgb[i] - compliment[i]) > GREY_TOLERANCE) isGrey = false;<br /> 19 }<br /> 20<br /> 21 if (isGrey) {<br /> 22 for (int i = 0; i < rgb.length; i++) {<br /> 23 compliment[i] = (rgb[i] >= 128) ? rgb[i] - 128 : rgb[i] + 128;<br /> 24 }<br /> 25 }<br /> 26<br /> 27 return compliment;<br /> 28<br /> 29 }<br /> 30 }<br /></pre> </div> <div class="header">Notes:</div> <p> We need to deal with two separate cases here: the color may meet the given definition of grey, or it may not. The trouble is, we won't know if it's considered grey or not until we've examined all three colors. We'll start by assuming that the color is grey, and then flip the isGrey flag to false if we find a red, green, or blue value whose compliment exceeds GREY_TOLERANCE. </p> <p> We start by creating the output array named compliment. Then for each value in rgb, we calculate the corresponding compliment by subtracting the color in the current position of rgb from RGB_MAX. If the difference between a color and its compliment exceeds GREY_TOLERANCE, then we'll set isGrey to false. </p> <p> After red, green, and blue have all been evaluated, if isGrey is still true then we need to handle it according to the instructions for a grey color. For each position in rgb, if the value is greater than or equal to 128, we subtract 128, otherwise add 128. This value will overwrite the value in compliment[] that was stored earlier. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-89856801869693634942015-10-10T22:44:00.000-04:002015-10-10T22:44:01.764-04:00Removal<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1973" target="_blank">TopCoder Problem Statement - Removal</a> </td> </tr> <tr><td>Single Round Match 177 Round 1 - Division I, Level Two</td></tr> <tr><td>Single Round Match 177 Round 1 - Division II, Level Three</td></tr> </table> </p> <div class="header">Overview:</div> <p> Remove items from a list filling in the space by shifting all following elements up one. Return the item at the given position after all the removals. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class Removal {<br /> 2<br /> 3 public int finalPos(int n, int k, String[] remove) {<br /> 4<br /> 5 for (int i = remove.length - 1; i >= 0; i--) {<br /> 6<br /> 7 String[] hilo = remove[i].split("-");<br /> 8 int lo = Integer.parseInt(hilo[0]);<br /> 9 int hi = Integer.parseInt(hilo[1]);<br /> 10<br /> 11 if (k >= lo) {<br /> 12 k += (hi - lo + 1);<br /> 13 }<br /> 14<br /> 15 // If k < 0, then we've overflowed, return a -1.<br /> 16 if ((k > n) || (k < 0)) return -1;<br /> 17 }<br /> 18<br /> 19 return k;<br /> 20 }<br /> 21<br /> 22 }<br /></pre> </div> <div class="header">Notes:</div> <p> You might assume that you could use a built-in data structure, such as a linked list to solve the problem. Just initialize the list, and then let it do the removals for you. However, it pays to take a look at the constraints first. The number of elements can be up to 2,000,000,000 which is way too much to fit into the allotted 64MB. </p> <p> The solution is to think about how k's position changes as elements in front of it are removed. Elements that are greater than k don't matter when they're removed since these won't affect k's position. </p> <p> We start at the end work backwards through each String in remove. First, parse out the lo and hi elements of the string. Then, if lo is less than k, we'll adjust k's position accordingly. The number of elements removed is given by (hi - lo + 1). So, we increase k's value by that amount to get it's position before the removals. </p> <p> After working backward through all the elements in remove, the value of k will be it's original starting position which is the value we want to return. </p> <p> Be careful to check the value of k after each addition. If it's ever greater than n, we'll return -1. The addition could also cause an overflow. You could convert k to a long to prevent this, or just check the value to see if it becomes negative. Since the value of hi will be 2 billion or less, it will fit into an int. Adding 2 billion to a positive int and causing an overflow will always result in a negative number. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-49154962613610409742015-10-08T23:25:00.003-04:002015-10-08T23:25:59.121-04:00Matching<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=2249" target="_blank">TopCoder Problem Statement - Matching</a> </td> </tr> <tr><td>Single Round Match 176 Round 1 - Division I, Level One</td></tr> <tr><td>Single Round Match 176 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Find the card which completes the pattern. For each group of characteristics, the matching card must either share the trait with the other two cards, or all three cards must have a different value. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class Matching {<br /> 2<br /> 3 private static final String[][] TRAITS = {<br /> 4 {"CIRCLE", "SQUIGGLE", "DIAMOND"},<br /> 5 {"BLUE", "RED", "GREEN"},<br /> 6 {"SOLID", "STRIPED", "EMPTY"},<br /> 7 {"ONE", "TWO", "THREE"}<br /> 8 };<br /> 9<br /> 10 public String[] findMatch(String[] first, String[] second) {<br /> 11<br /> 12 String[] result = new String[4];<br /> 13<br /> 14 for (int i = 0; i < TRAITS.length; i++) {<br /> 15 result[i] = getMatch(first[i], second[i], TRAITS[i]);<br /> 16 }<br /> 17<br /> 18 return result;<br /> 19<br /> 20 }<br /> 21<br /> 22 private static String getMatch(String s1, String s2, String[] traits) {<br /> 23<br /> 24 /*<br /> 25 * If the two strings are equal, then return that string.<br /> 26 */<br /> 27 if (s1.equals(s2)) return s1;<br /> 28<br /> 29 /*<br /> 30 * Otherwise, return the string that is not s1 or s2<br /> 31 */<br /> 32 for (int i = 0; i < traits.length; i++) {<br /> 33 if (!traits[i].equals(s1) && !traits[i].equals(s2))<br /> 34 return traits[i];<br /> 35 }<br /> 36<br /> 37 return null;<br /> 38<br /> 39 }<br /> 40 }<br /></pre> </div> <div class="header">Notes:</div> <p> This is one of those problems where reading the description makes you think it's going to be much more difficult than the problem actually is. All we need to do is for each of the four traits (shape, color, fill pattern, and count) give the value of the string if the first and second card have the same value. Or, if the first and second cards have different values, then we give the third (or odd man out) value. </p> <p> The for loop in the findMatch() method just walks through each of the four traits, and calls getMatch() to insert the correct value into the result array. </p> <p> getMatch() compares the two strings, and if they're equal returns that value. Otherwise, it looks through the values given in traits for a string that does not match s1 and does not match s2. Note that we should never reach the return null statement on line 37, but it needs to be there to satisfy the compiler. </p> <p> Nothing difficult here. Getting through the description actually took longer than writing the code. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-43834754306891417922015-10-06T23:21:00.001-04:002015-10-06T23:21:34.489-04:00Stairs<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=2011" target="_blank">TopCoder Problem Statement - Stairs</a> </td> </tr> <tr> <td>Single Round Match 177 Round 1 - Division II, Level One></td> </tr> </table> </p> <div class="header">Overview:</div> <p> Count the number of combinations of risers and treads that can lead to a staircase of the given dimensions. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class Stairs {<br /> 2<br /> 3 public int designs(int maxHeight, int minWidth, int totalHeight, int totalWidth) {<br /> 4<br /> 5 int count = 0;<br /> 6<br /> 7 for (int riserHeight = 1; (riserHeight <= maxHeight); riserHeight++) {<br /> 8 if ((totalHeight % riserHeight) != 0) continue;<br /> 9<br /> 10 int numTreads = (totalHeight / riserHeight) - 1;<br /> 11<br /> 12 if ((numTreads == 0) ||<br /> 13 ((totalWidth % numTreads) != 0) ||<br /> 14 ((totalWidth / numTreads) < minWidth)) continue;<br /> 15 count++;<br /> 16 }<br /> 17<br /> 18 return count;<br /> 19 }<br /> 20 }<br /></pre> </div> <div class="header">Notes:</div> <p> Note that the size of both the risers and treads must be integers, and that they are at most 1,000. This means that a brute force search is certainly possible. We'll loop through all possible heights and count the number of configurations that are possible. </p> <p> For each riser height, we first check to see if it evenly divides the total height. If not, then we can continue on with the next height. If so, then we'll look at the treads. </p> <p> The number of treads will be one less than the number of risers. We can compute the number of risers with (totalHeight / riserHeight). Then just subtract one from that result to get the number of treads. </p> <p> Next, we look for ways to discount the current number of risers and treads. The problem statement says that their must be at least one tread (and riser), so we can throw out any cases where the number of treads is 0. Again, just like with the risers, the total width must be evenly divided by the number of treads, so we can skip any case where that isn't true. And finally, any case where the width of each tread (totalWidth / numTreads) is smaller than the minimum allowed can also be skipped. </p> <p> Passing each of those tests, leaves us with a valid configuration, so increment the counter. After looping throug all possibilities, return the value in the counter. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-60366049031159044912015-08-30T15:24:00.003-04:002015-08-30T15:24:48.172-04:00InstantRunoff<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=2244" target="_blank">TopCoder Problem Statement - InstantRunoff</a> </td> </tr> <tr><td>Single Round Match 175 Round 1 - Division I, Level One</td></tr> <tr><td>Single Round Match 175 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine the winner of a run off election by following the given rules. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1<br /> 1 import java.util.HashMap;<br /> 2 import java.util.HashSet;<br /> 3 import java.util.Map;<br /> 4 import java.util.Set;<br /> 5<br /> 6 public class InstantRunoff {<br /> 7<br /> 8 public String outcome(String candidates, String[] ballots) {<br /> 9<br /> 10 Set<Character> activeCandidates = new HashSet<>();<br /> 11<br /> 12 for (Character c : candidates.toCharArray()) {<br /> 13 activeCandidates.add(c);<br /> 14 }<br /> 15<br /> 16 while (true) {<br /> 17<br /> 18 // Count the number of first place votes for each candidate.<br /> 19 Map<Character, Integer> firstPlaceVotes = new HashMap<>();<br /> 20<br /> 21 for (Character c : activeCandidates) {<br /> 22 firstPlaceVotes.put(c, 0);<br /> 23 }<br /> 24<br /> 25 for (String b : ballots) {<br /> 26 Character c;<br /> 27<br /> 28 c = b.charAt(0);<br /> 29 firstPlaceVotes.put(c, firstPlaceVotes.get(c) + 1);<br /> 30 }<br /> 31<br /> 32 // Do we have a clear winner?<br /> 33 for (Character c : activeCandidates) {<br /> 34 if (firstPlaceVotes.get(c) >=<br /> 35 ((ballots.length / 2) + 1)) {<br /> 36 return "" + c;<br /> 37 }<br /> 38 }<br /> 39<br /> 40 // Get the least first place votes<br /> 41 int minFirstPlaceVotes = Integer.MAX_VALUE;<br /> 42<br /> 43 for (Character c : activeCandidates) {<br /> 44 minFirstPlaceVotes = Math.min(minFirstPlaceVotes,<br /> 45 firstPlaceVotes.get(c));<br /> 46 }<br /> 47<br /> 48 // Remove all candidates with the most last place votes<br /> 49 Set<Character> toRemove = new HashSet<>();<br /> 50 for (Character c : activeCandidates) {<br /> 51 if (firstPlaceVotes.get(c) == minFirstPlaceVotes)<br /> 52 toRemove.add(c);<br /> 53 }<br /> 54<br /> 55 for (Character c : toRemove) {<br /> 56 activeCandidates.remove(c);<br /> 57 for (int i = 0; i < ballots.length; i++) {<br /> 58 ballots[i] = ballots[i].replaceFirst("" + c, "");<br /> 59 }<br /> 60 }<br /> 61<br /> 62 if (activeCandidates.size() == 0) return "";<br /> 63 }<br /> 64<br /> 65 }<br /> 66<br /> 67 }<br /></pre> </div> <div class="header">Notes:</div> <p> This solution basically just follows the rules for the election as given in the problem statement. First, it creates a set of remaining candidates, then it enters a while loop which will not terminate until either a winner is found, or the set of remaining candidates becomes empty. </p> <p> For each iteration of the loop, we count up the number of first place votes that each active candidate has received. If any of the candidates receives more than half of the possible votes, then they are declared the winner. Be careful in checking for a majority, the equation on lines 34 and 35 is easy to get wrong. </p> <p> If there is no clear winner, then we look for the least number of first place votes, and remove any candidate that has that number of first place votes. Here, we remove those candidates from both the active candidates set, as well as from all the ballots. The easiest, although perhaps not the most efficient way is to do the replacement on line 58. </p> <p> Finally, if there are no more active candidates, then we return the empty string. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-25991998636923880162015-08-30T15:07:00.000-04:002015-08-30T15:07:02.716-04:00ClockWalk<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=2241" target="_blank">TopCoder Problem Statement - ClockWalk</a> </td> </tr> <tr><td>Single Round Match 175 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine the ending time after a series of jumps forward and back. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class ClockWalk {<br /> 2<br /> 3 public int finalPosition(String flips) {<br /> 4 int result = 0;<br /> 5<br /> 6 for (int i = 0; i < flips.length(); i++) {<br /> 7 if (flips.charAt(i) == 'h') result += i + 1;<br /> 8 else result -= i + 1;<br /> 9 }<br /> 10<br /> 11 result %= 12;<br /> 12<br /> 13 return (result <= 0) ? (result + 12) : result;<br /> 14 }<br /> 15<br /> 16 }<br /></pre> </div> <div class="header">Notes:</div> <p> For each character in flips we want to either move forward or backward around a clock face. The number of steps is 1 plus the index of the current character. 1 for position 0, 2 for position 1, etc. </p> <p> If the character is 'h', we use += to advance forward. Otherwise -= to move backward. </p> <p> After all the moves have been made, we mod the result by 12, and if the result is less than or equal to 0, we add 12. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-74478816615148551532015-08-10T17:41:00.000-04:002015-08-10T17:41:26.592-04:00MineField<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1877" target="_blank">TopCoder Problem Statement - MineField</a> </td> </tr> <tr><td>Single Round Match 169 Round 1 - Division I, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Given a set of coordinates representing bombs, generate a board suitable for playing MineField. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 import java.util.*;<br /> 2 import java.math.*;<br /> 3 import static java.lang.Math.*;<br /> 4<br /> 5 public class MineField {<br /> 6<br /> 7 private static final int SIZE = 9;<br /> 8 private static final char MINE_CHAR = 'M';<br /> 9<br /> 10 char[][] mineField = new char[SIZE][SIZE];<br /> 11<br /> 12 public String[] getMineField(String mineLocations) {<br /> 13<br /> 14 // Initialize the mine Field<br /> 15 for (int row = 0; row < SIZE; row++) {<br /> 16 for (int col = 0; col < SIZE; col++) {<br /> 17 mineField[row][col] = '0';<br /> 18 }<br /> 19 }<br /> 20<br /> 21 // Converts all parenthesis and commas to spaces.<br /> 22 String input = mineLocations<br /> 23 .replaceAll("\\(", " ")<br /> 24 .replaceAll("\\)", " ")<br /> 25 .replaceAll(",", " ");<br /> 26<br /> 27 // A scanner that uses spaces as the delimiter<br /> 28 Scanner sc = new Scanner(input);<br /> 29 sc.useDelimiter("\\s+");<br /> 30<br /> 31 // Read all the coordinates and add the mines.<br /> 32 while (sc.hasNextInt()) {<br /> 33 int row = sc.nextInt();<br /> 34 int col = sc.nextInt();<br /> 35 addMine(row,col);<br /> 36 }<br /> 37<br /> 38 // Create the return value.<br /> 39 String[] result = new String[SIZE];<br /> 40<br /> 41 for (int i = 0; i < SIZE; i++) {<br /> 42 result[i] = new String(mineField[i]);<br /> 43 }<br /> 44<br /> 45 return result;<br /> 46 }<br /> 47<br /> 48 private void addMine(int row, int col) {<br /> 49<br /> 50 mineField[row][col] = MINE_CHAR;<br /> 51<br /> 52 /*<br /> 53 * Increment the value in all surrounding squares<br /> 54 * checking to ensure that we stay within the bounds<br /> 55 * of the board, and that the other square is not<br /> 56 * already marked as a mine.<br /> 57 */<br /> 58 for (int r = row - 1; r <= row + 1; r++) {<br /> 59 for (int c = col - 1; c <= col + 1; c++) {<br /> 60<br /> 61 if ((r >= 0) && (r < SIZE) &&<br /> 62 (c >= 0) && (c < SIZE) &&<br /> 63 (mineField[r][c] != MINE_CHAR)) {<br /> 64<br /> 65 // Increase the value of the neighbor.<br /> 66 mineField[r][c]++;<br /> 67 }<br /> 68 }<br /> 69 }<br /> 70<br /> 71 }<br /> 72 }<br /> </pre> </div> <div class="header">Notes:</div> <p> This is a pretty easy Divison 1 problem, with just a few tricks to overcome. First, I'll begin by saying I was tripped up by the ordering of the coordinates. I assumed that the numbers were in the form (x, y). They're not. The description says they're given as (row, col). In other words (y, x). After seeing my output sideways, I tracked the error down and fixed it. </p> <p> The first problem to solve is parsing the input. For this, first I replaced all parenthesis and commas with spaces. Then I created a scanner that uses whitespace as the delimeter. With that, I can just use a pair of nextInt() calls to get the coordinates until they run out. </p> <p> I find these problems much easier to work with using char arrays. I'll often convert the given String[] into a char[][] just to simplify. In this case, I represent the mineField as a char[][] and then convert it to a String[] when returning the result. </p> <p> With the coordinates, and the mineField, the next problem is to add the mine to the current board. That's just a matter of setting that location to 'M', and then updating all the neighbors. I use a nested for loop to visit all the neighbors of the given location working top to bottom and left to right. For each location, check to ensure that we're not outside the boundaries of the array, and that the square is not already marked as a mine. If that test passes, then increment the value stored there. Since we can treat chars as ints here, mineField[r][c]++ will work nicely. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-33802017300971286722015-08-08T00:03:00.001-04:002015-08-08T00:03:16.293-04:00CrossWord<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=2322" target="_blank">TopCoder Problem Statement - CrossWord</a> </td> </tr> <tr><td>Single Round Match 174 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine how many slots of a given length appear horizontally in a given crossword puzzle. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class CrossWord {<br /> 2<br /> 3 public int countWords(String[] board, int size) {<br /> 4<br /> 5 int total = 0;<br /> 6<br /> 7 /*<br /> 8 * Sum up the number of horizontal slots in each<br /> 9 * of the rows in the board.<br /> 10 */<br /> 11 for (String s : board) {<br /> 12 total += countHorizontalSlots(s, size);<br /> 13 }<br /> 14<br /> 15 return total;<br /> 16 }<br /> 17<br /> 18 /*<br /> 19 * Count the number of horizontal slots in a<br /> 20 * single row of the board.<br /> 21 */<br /> 22 private static int countHorizontalSlots(String s, int size) {<br /> 23<br /> 24 // Number of horizontal slots found.<br /> 25 int num = 0;<br /> 26<br /> 27 // Number of continuous spaces found.<br /> 28 int spaces = 0;<br /> 29<br /> 30 // Loop through each character in the given string.<br /> 31 for (int i = 0; i < s.length(); i++) {<br /> 32<br /> 33 /*<br /> 34 * An 'X' marks the end of a slot. So when an<br /> 35 * 'X' is encountered, if the number of spaces<br /> 36 * matches the size we're looking for, then<br /> 37 * increase the count.<br /> 38 * Set spaces to 0 whenever an 'X' is found.<br /> 39 */<br /> 40 if (s.charAt(i) == 'X') {<br /> 41 if (spaces == size) {<br /> 42 num++;<br /> 43 }<br /> 44 spaces = 0;<br /> 45<br /> 46 } else {<br /> 47<br /> 48 /*<br /> 49 * If it's not an 'X', then increment the number<br /> 50 * of open spaces found.<br /> 51 */<br /> 52 spaces++;<br /> 53 }<br /> 54<br /> 55 }<br /> 56<br /> 57 /*<br /> 58 * This condition is met when the slot leads up to the<br /> 59 * right edge of the board.<br /> 60 */<br /> 61 if (spaces == size) {<br /> 62 num++;<br /> 63 }<br /> 64<br /> 65 return num;<br /> 66 }<br /> 67 }<br /></pre> </div> <div class="header">Notes:</div> <p> The first step is to divide the crossword up into individual rows. For each row, we'll add up the number of slots, and then return the sum. </p> <p> The count the slots in an single row we'll step through each character of the given string looking for 'X's since the 'X' character terminates a slot. If any character other than an 'X' is encountered, we simply increase the number of spaces seen. When an 'X' appears, we check to see if the number of spaces matches what we're looking for. If so, increment the count for this line. </p> <p> Be careful to include the case where the slot ends at the end of the string. The last check - "if (spaces == size)" takes care of this. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-37659135245435879552015-07-30T14:29:00.001-04:002015-07-30T14:29:07.693-04:00WordForm<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=" target="_blank">TopCoder Problem Statement - WordForm</a> </td> </tr> <tr><td>Single Round Match 173 Round 1 - Division I, Level One</td></tr> <tr><td>Single Round Match 173 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Detect vowels and consonants in a word. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class WordForm {<br /> 2<br /> 3 public String getSequence(String word) {<br /> 4<br /> 5 char[] cvArray = new char[word.length()];<br /> 6<br /> 7 boolean prevIsVowel = true;<br /> 8<br /> 9 for (int i = 0; i < word.length(); i++) {<br /> 10 cvArray[i] = (prevIsVowel = isVowel(word.charAt(i), prevIsVowel)) ? 'V' : 'C';<br /> 11 }<br /> 12<br /> 13 // Remove duplicate characters<br /> 14 return new String(cvArray).replaceAll("([CV])\\1+", "$1");<br /> 15 }<br /> 16<br /> 17 private static boolean isVowel(Character c, boolean prevIsVowel) {<br /> 18<br /> 19 c = Character.toUpperCase(c);<br /> 20<br /> 21 if ((c.equals('A')) || (c.equals('E')) ||<br /> 22 (c.equals('I')) || (c.equals('O')) ||<br /> 23 (c.equals('U'))) return true;<br /> 24<br /> 25 if (!c.equals('Y')) return false;<br /> 26<br /> 27 return !prevIsVowel;<br /> 28 }<br /> 29 }<br /></pre> </div> <div class="header">Notes:</div> <p> The problem can be solved by breaking it up into two pieces. First, obviously we're going to need a method to determine if a character is a consonant or vowel. This is handled by isVowel(). isVowel() first converts the character to upper-case, and then compares it to the standard vowels A, E, I, O, and U. If it matches one of these, or if it doesn't and also is not a 'Y' then we're done. 'Y's are the only tricky letter. </p> <p> To determine if 'Y' is a vowel or not, isVowel() requires a boolean denoting whether the previous character was a vowel or not. We can set prevIsVowel's initial value to true since the behavior of a 'Y' at the beginning of a string is the same as a 'Y' following a vowel. </p> <p> With a reliable method of determining consonants and vowels, we just need to construct the return String, and the only challenge there is eliminating duplicates. One way to do this would be to keep track of the last character, and only append the next character if it differed. An easier way is to just add all the characters, and then use a regular expression to remove the duplicates. This is done in the replaceAll() method of the return statement. </p> <p> If you're not familiar with the assignment on line 10, all this does is assign the result of isVowel() to both prevIsVowel and cvArray[i] in one line. First, isVowel() is evaluated and the result is assigned to prevIsVowel. The result of this assignment, which is either true or false, is then assigned to cvArray[i]. With that, we've put the correct character (either a 'V' or a 'C') into the array, and set prevIsVowel to the correct value for the next call into isVowel(). </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-14078628519448840702015-07-29T18:58:00.003-04:002015-07-29T18:58:53.042-04:00ProgressBar<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1975" target="_blank">TopCoder Problem Statement - ProgressBar</a> </td> </tr> <tr><td>Single Round Match 173 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Fill in a progress bar to show the fraction of completed time vs. total time estimated to complete a task. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class ProgressBar {<br /> 2<br /> 3 public static final int NUM_MARKERS = 20;<br /> 4 private static final char FILL_CHAR = '#';<br /> 5 private static final char EMPTY_CHAR = '.';<br /> 6<br /> 7<br /> 8 public String showProgress(int[] taskTimes, int tasksCompleted) {<br /> 9<br /> 10 int totalTime = 0;<br /> 11 int completedTime = 0;<br /> 12<br /> 13 /*<br /> 14 * Count the time for all completed tasks and the<br /> 15 * overall total time.<br /> 16 */<br /> 17 for (int i = 0; i < taskTimes.length; i++) {<br /> 18 totalTime += taskTimes[i];<br /> 19<br /> 20 if (tasksCompleted > i) {<br /> 21 completedTime = totalTime;<br /> 22 }<br /> 23 }<br /> 24<br /> 25 int numberToFill = NUM_MARKERS * completedTime / totalTime;<br /> 26<br /> 27 /*<br /> 28 * Create our return array. Fill in the characters that should<br /> 29 * be filled in, then mark the rest as empty.<br /> 30 */<br /> 31 char[] chars = new char[NUM_MARKERS];<br /> 32<br /> 33 for (int i = 0; i < numberToFill; i++) {<br /> 34 chars[i] = FILL_CHAR;<br /> 35 }<br /> 36<br /> 37 for (int i = numberToFill; i < NUM_MARKERS; i++) {<br /> 38 chars[i] = EMPTY_CHAR;<br /> 39 }<br /> 40<br /> 41 return new String(chars);<br /> 42 }<br /> 43 }<br /></pre> </div> <div class="header">Notes:</div> <p> The first step is to sum the time taken so far and the total time. This can be done in one pass of the given taskTimes array. </p> <p> With these, we can determine the number of characters that must be filled in using the formula: </p> <p> NUM_MARKERS * completedTime / totalTime </p> <p> Note that this is using integer division, so the result will automatically be rounded down for us. </p> <p> Then it's just a matter of filling in the first numberToFill characters, and setting the rest to empty. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-6255165559004757862015-07-22T16:30:00.001-04:002015-07-22T16:30:27.383-04:00Cubism<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1815" target="_blank">TopCoder Problem Statement - Cubism</a> </td> </tr> <tr><td>Single Round Match 172 Round 1 - Division II, Level Three</td></tr> </table> </p> <div class="header">Overview:</div> <p> Count the number of lines that can be formed in a cube where the line's length equals the length of a side of the cure, and all location along the line match a given color. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1<br /> 2<br /> 3 public class Cubism {<br /> 4<br /> 5 public int lines(String[] lattice, String color) {<br /> 6<br /> 7 int size = lattice.length;<br /> 8 char c = "black".equals(color) ? 'B' : 'W';<br /> 9<br /> 10 /*<br /> 11 * The problem becomes much easier if we transform the<br /> 12 * given String[] into a 3-Dimensional array<br /> 13 * of chars.<br /> 14 */<br /> 15 char[][][] cube = new char[size][size][size];<br /> 16<br /> 17 for (int x = 0; x < size; x++) {<br /> 18 for (int y = 0; y < size; y++) {<br /> 19 for (int z = 0; z < size; z++) {<br /> 20 cube[x][y][z] = lattice[x].charAt((y * size) + z);<br /> 21 }<br /> 22 }<br /> 23 }<br /> 24<br /> 25 int numLines = 0;<br /> 26<br /> 27 /*<br /> 28 * Count the number of lines that begin at each location.<br /> 29 */<br /> 30 for (int x = 0; x < size; x++) {<br /> 31 for (int y = 0; y < size; y++) {<br /> 32 for (int z = 0; z < size; z++) {<br /> 33 numLines += countLinesStartingAt(cube, x, y, z, c);<br /> 34 }<br /> 35 }<br /> 36 }<br /> 37<br /> 38 /*<br /> 39 * Each line will be counted twice, once starting from<br /> 40 * each end point, so divide the result in half.<br /> 41 */<br /> 42 return numLines / 2;<br /> 43 }<br /> 44<br /> 45 /*<br /> 46 * Count the number of lines starting from the given coordinate. The line<br /> 47 * must be of the given color c.<br /> 48 */<br /> 49 private static int countLinesStartingAt(char[][][] cube,<br /> 50 int x, int y, int z,<br /> 51 char c) {<br /> 52<br /> 53 int numLines = 0;<br /> 54<br /> 55 /*<br /> 56 * We'll generate the 27 directions that the row could stretch out in<br /> 57 * by using deltaX, deltaY, and deltaZ.<br /> 58 */<br /> 59 for (int deltaX = -1; deltaX < 2; deltaX++) {<br /> 60 for (int deltaY = -1; deltaY < 2; deltaY++) {<br /> 61 for (int deltaZ = -1; deltaZ < 2; deltaZ++) {<br /> 62 if (isLine(cube, x, y, z, deltaX, deltaY, deltaZ, c)) {<br /> 63 numLines++;<br /> 64 }<br /> 65 }<br /> 66 }<br /> 67 }<br /> 68 return numLines;<br /> 69 }<br /> 70<br /> 71 /*<br /> 72 * Returns true if a line originating at (x,y,z) of size cube.length and moving<br /> 73 * in the direction given by deltaX, deltaY, and deltaZ can be formed.<br /> 74 * All position along the line must match color c.<br /> 75 */<br /> 76 private static boolean isLine(char[][][] cube,<br /> 77 int x, int y, int z,<br /> 78 int deltaX, int deltaY, int deltaZ,<br /> 79 char c) {<br /> 80<br /> 81 // It's not a line if we never move from the origin.<br /> 82 if ((deltaX == 0) && (deltaY == 0) && (deltaZ == 0)) return false;<br /> 83<br /> 84 for (int i = 0; i < cube.length; i++) {<br /> 85<br /> 86 // Check that we stay within bounds.<br /> 87 if ((x < 0) || (x >= cube.length)) return false;<br /> 88 if ((y < 0) || (y >= cube.length)) return false;<br /> 89 if ((z < 0) || (z >= cube.length)) return false;<br /> 90<br /> 91 // Check the color matches.<br /> 92 if (cube[x][y][z] != c) return false;<br /> 93<br /> 94 // Move to the next location.<br /> 95 x += deltaX;<br /> 96 y += deltaY;<br /> 97 z += deltaZ;<br /> 98 }<br /> 99<br /> 100 return true;<br /> 101 }<br /> 102 }<br /></pre> </div> <div class="header">Notes:</div> <p> This problem becomes very easy once you break it down into smaller steps. The first task is to take the unwieldly String[] and convert it into an easy to use 3 dimensional array of chars. This is handled on lines 15-23. Nothing trick here, except for a little bit of math to get the right character out of the String. </p> <p> With our 3-D array, we can now loop through each position and count the number of lines starting at that position. Note that we'll count each row twice. Once starting from each end and going to the other. </p> <p> The countLinesStartingAt() method does just that. Given a 3-D coordinate, it returns the number of lines starting from that position. Rather than writing out the 27 directions that we could move out from for any given position, I have three nested loops and the variables deltaX, deltaY, and deltaZ. Each of these variables moves from -1 to 1. </p> <p> With that, we call isLine() providing the staring point, direction, and color. isLine() just checks that we stay within the confines of the cube and stay on the correct color as we move along the line. </p> <p> Nothing really difficult here. It could probably have been a Division 2 Level 2. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-13938611666816387782015-07-22T15:28:00.000-04:002015-07-22T15:28:47.237-04:00BadClock<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1969" target="_blank">TopCoder Problem Statement - BadClock</a> </td> </tr> <tr><td>Single Round Match 172 Round 1 - Division I, Level One</td></tr> <tr><td>Single Round Match 172 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine how many hours it will take a clock to show the correct time given how far off it is initially and how many seconds it gains/loses per hour. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1<br /> 2<br /> 3 public class BadClock {<br /> 4<br /> 5 public double nextAgreement(<br /> 6 String trueTime, String skewTime, int hourlyGain) {<br /> 7<br /> 8 String[] trueString = trueTime.split(":");<br /> 9 String[] skewString = skewTime.split(":");<br /> 10<br /> 11 /*<br /> 12 * Number of seconds that skewTime is behind trueTime.<br /> 13 * If skewSeconds is negative, then skewTime is ahead<br /> 14 * of trueTime.<br /> 15 */<br /> 16 int skewSeconds = 0;<br /> 17<br /> 18 skewSeconds =<br /> 19 (Integer.parseInt(trueString[0]) -<br /> 20 Integer.parseInt(skewString[0])) * 60 * 60;<br /> 21<br /> 22 skewSeconds +=<br /> 23 (Integer.parseInt(trueString[1]) -<br /> 24 Integer.parseInt(skewString[1])) * 60;<br /> 25<br /> 26 skewSeconds += Integer.parseInt(trueString[2]) -<br /> 27 Integer.parseInt(skewString[2]);<br /> 28<br /> 29 if (skewSeconds == 0) return 0.0;<br /> 30<br /> 31 if ((skewSeconds > 0) && (hourlyGain < 0)) {<br /> 32 // Clock is behind, and losing.<br /> 33 skewSeconds -= 12 * 60 * 60; // Move skewTime ahead 12 hours<br /> 34<br /> 35 } else if ((skewSeconds < 0) && (hourlyGain > 0)) {<br /> 36 // Clock is ahead, and gaining<br /> 37 skewSeconds += 12 * 60 * 60; // Move skewTime behind 12 hours<br /> 38 }<br /> 39<br /> 40 return (double) skewSeconds / (double) hourlyGain;<br /> 41<br /> 42 }<br /> 43 }<br /></pre> </div> <div class="header">Notes:</div> <p> The first step is to determine how many seconds the skewed clock is away from the true time. This is calculated on lines 18-27 and is stored in skewSeconds. Note that if skewSeconds is positive then the skewed clock is behind true time. If skewSeconds is negative, then the skewed clock is ahead of the true time. </p> <p> If skewSeconds is 0, then we can simply return 0. Otherwise, we'll want to divide the number of seconds the two clocks are off by the hourlyGain. This is fine if the skewed clock is ahead and hourlyGain is negative; or if the skewed clock is behin and hourlyGain is positive. But we must account for two other cases as well. </p> <p> If the skewed clock is ahead, and the hourlyGain is positive, then it's distance ahead will keep increasing. To fix this, we can just set the skewed clock back 12 hours. Similary, if the skewed clock is behind, and the hourlyGain is negative, we can adjust the skewed clock ahead 12 hours. Be careful with the signs here, it can get a little confusing. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-8307719389592563102015-07-21T19:01:00.003-04:002015-07-21T19:03:50.619-04:00SkipRope<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1968" target="_blank">TopCoder Problem Statement - SkipRope</a> </td> </tr> <tr><td>Single Round Match 172 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Find the two numbers in an array that are closest to the given number. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 import java.util.Arrays;<br /> 2<br /> 3 public class SkipRope {<br /> 4<br /> 5 public int[] partners(int[] candidates, int height) {<br /> 6<br /> 7 int[] heights = {Integer.MAX_VALUE, Integer.MAX_VALUE};<br /> 8<br /> 9 for (int c : candidates) {<br /> 10 if (isCloser(c, heights[0], height)) {<br /> 11<br /> 12 /*<br /> 13 * If closer that the closest, then bump the closest<br /> 14 * into 2nd place, and set the candidate to be<br /> 15 * the new closest.<br /> 16 */<br /> 17 heights[1] = heights[0];<br /> 18 heights[0] = c;<br /> 19<br /> 20 } else if (isCloser(c, heights[1], height)) {<br /> 21<br /> 22 // Set 2nd place to be the candidate.<br /> 23 heights[1] = c;<br /> 24 }<br /> 25 }<br /> 26<br /> 27 Arrays.sort(heights);<br /> 28<br /> 29 return heights;<br /> 30 }<br /> 31<br /> 32 /*<br /> 33 * Returns true if the candidate is closer in height than the current<br /> 34 * person. If the two are the same distance apart, then ties go<br /> 35 * to the taller person.<br /> 36 */<br /> 37 private static boolean isCloser(int candidate, int current, int height) {<br /> 38<br /> 39 int diffCandidate = Math.abs(height - candidate);<br /> 40 int diffCurrent = Math.abs(height - current);<br /> 41<br /> 42 if (diffCandidate < diffCurrent) return true;<br /> 43<br /> 44 if (diffCandidate > diffCurrent) return false;<br /> 45<br /> 46 // Ties go to the taller person.<br /> 47 return candidate > current;<br /> 48<br /> 49 }<br /> 50 }<br /></pre> </div> <div class="header">Notes:</div> <p> The solution starts by creating an array (heights) to store the two closest numbers. It sets their initial values to Integer.MAX_VALUE to ensure they're far enough away from our height that the first two numbers seen are guaranteed to be closers. </p> <p> Then we make one pass through the list of candidate heights. If the height is closer than the value in position 0, we move the closest into the second closest position, and insert our candidate in position 0 as the next closest height. </p> <p> If the height is not the closest, but it is closer than the second closest, then we simply replace the the height in position 1 with our current candidate's height. </p> <p> The method isCloser determines if the value is candidate is closer to height than the value of current. Note that we must take the absolute value of the difference. In the event of a tie closer is determined by if candidate is greater than current. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div> Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-32058478526337467862015-07-19T17:14:00.001-04:002015-07-19T17:14:15.450-04:00TextEditor<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1942" target="_blank">TopCoder Problem Statement - TextEditor</a> </td> </tr> <tr><td>Single Round Match 171 Round 1 - Division II, Level Three</td></tr> </table> </p> <div class="header">Overview:</div> <p> Format text into 2 columns. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 import java.util.ArrayList;<br /> 2 import java.util.List;<br /> 3 <br /> 4 public class TextEditor {<br /> 5 <br /> 6 public String[] twoColumn(String[] text, int width) {<br /> 7 <br /> 8 List<String> allWords = new ArrayList<>();<br /> 9 <br /> 10 /*<br /> 11 * Put all words together into one long list.<br /> 12 */<br /> 13 for (String line : text) {<br /> 14 String[] wordsOnLine = line.trim().split("\\s+");<br /> 15 for (String word : wordsOnLine) {<br /> 16 allWords.add(word);<br /> 17 }<br /> 18 }<br /> 19 <br /> 20 /*<br /> 21 * Break the words up into lines so that no<br /> 22 * line is longer than the given width.<br /> 23 */<br /> 24 List<String> oneColumn = new ArrayList<>();<br /> 25 <br /> 26 StringBuilder sb = new StringBuilder(width);<br /> 27 <br /> 28 for (String word : allWords) {<br /> 29 <br /> 30 /*<br /> 31 * Nothing we can do if a word by itself cannot<br /> 32 * fit onto a line with the given width.<br /> 33 */<br /> 34 if (word.length() > width) {<br /> 35 throw new IllegalArgumentException(<br /> 36 "Word is too long to fit into column: " + word);<br /> 37 }<br /> 38 <br /> 39 /*<br /> 40 * If it's the first word, then always add it to<br /> 41 * the current line.<br /> 42 */<br /> 43 if (sb.length() == 0) {<br /> 44 sb.append(word);<br /> 45 <br /> 46 /*<br /> 47 * If a space plus the word would fit on the current<br /> 48 * line, then add it.<br /> 49 */<br /> 50 } else if (sb.length() + word.length() < width) {<br /> 51 sb.append(" ");<br /> 52 sb.append(word);<br /> 53 <br /> 54 /*<br /> 55 * Otherwise, start a new line.<br /> 56 */<br /> 57 } else {<br /> 58 oneColumn.add(sb.toString());<br /> 59 sb = new StringBuilder(width);<br /> 60 sb.append(word);<br /> 61 }<br /> 62 }<br /> 63 <br /> 64 /*<br /> 65 * If there's anything left over, add it to<br /> 66 * the final line.<br /> 67 */<br /> 68 if (sb.length() != 0) {<br /> 69 oneColumn.add(sb.toString());<br /> 70 }<br /> 71 <br /> 72 int i = 0;<br /> 73 <br /> 74 String[] result = new String[oneColumn.size()];<br /> 75 <br /> 76 /*<br /> 77 * Fill in the even numbered positions first, when<br /> 78 * the end is reached, come back and fill in the odds.<br /> 79 */<br /> 80 for (String s : oneColumn) {<br /> 81 result[i] = s;<br /> 82 i += 2;<br /> 83 if (i >= oneColumn.size()) i = 1;<br /> 84 }<br /> 85 <br /> 86 return result;<br /> 87 }<br /> 88 }<br /></pre> </div> <div class="header">Notes:</div> <p> A pretty easy problem for a Division 2 - Level 3. There's just two tricky things to take care of. First, we need to divide the input into columns that are no wider than the given width. To do this, I create a single list that contained all of the words. Note that the lines may have trailing and/or leading whitespace which we want to remove. Combining trim() with .split("\\s+") gives us the individual words nicely. </p> <p> Next, I divide the words by line into one column, such that the length of each line is less than or equal to width. This is done easily enough by the loop on lines 28 - 62. We just test the length of the current line plus a space plus the length of the next word. If that is greater than width, cut the line off and put the word at the beginning of the next line. </p> <p> Finally, we need to split the one column up into two columns with the lines interleaved. The easiest way to do this is to assign all the even numbered positions first. Then upon reaching the end of the list, come back to position 1, and start filling in the odd positions. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-69345395379026014442015-07-15T20:47:00.001-04:002015-07-15T20:49:36.682-04:00CrossCountry<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1950" target="_blank">TopCoder Problem Statement - CrossCountry</a> </td> </tr> <tr><td>Single Round Match 171 Round 1 - Division I, Level One </td></tr> <tr><td>Single Round Match 171 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine the order that teams place in a cross country meet given the finishing positions of each runner. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 import java.util.ArrayList;<br /> 2 import java.util.Collections;<br /> 3 import java.util.List;<br /> 4<br /> 5 public class CrossCountry {<br /> 6<br /> 7 private static final int MIN_FINISHERS = 5;<br /> 8 private static final int TIE_BREAKER_PLACE = MIN_FINISHERS + 1;<br /> 9<br /> 10 /*<br /> 11 * The Team class represents a team and contains methods for calculating<br /> 12 * it's score and comparing it to other teams.<br /> 13 */<br /> 14 class Team implements Comparable<Team> {<br /> 15<br /> 16 char name;<br /> 17 int score;<br /> 18 int numFinishers;<br /> 19 int tieBreaker;<br /> 20<br /> 21 public Team(char name) {<br /> 22 this.name = name;<br /> 23 }<br /> 24<br /> 25 public void addFinisher(int score) {<br /> 26<br /> 27 // Only the top 5 runner contribute to the score.<br /> 28 if (numFinishers < MIN_FINISHERS) {<br /> 29 this.score += score;<br /> 30<br /> 31 // Store the 6th finisher's position in tieBreaker.<br /> 32 } else if (numFinishers == MIN_FINISHERS) {<br /> 33 tieBreaker = score;<br /> 34 }<br /> 35<br /> 36 numFinishers++;<br /> 37 }<br /> 38<br /> 39 // Assumes that both Teams have at least five finishers.<br /> 40 @Override<br /> 41 public int compareTo(Team o) {<br /> 42<br /> 43 if (this.score != o.score) return new Integer(score).compareTo(o.score);<br /> 44<br /> 45 // This team does not have a 6th place finisher, but the other does.<br /> 46 if ((numFinishers < TIE_BREAKER_PLACE) && (o.numFinishers >= TIE_BREAKER_PLACE)) return 1;<br /> 47<br /> 48 // This team has a 6th place finisher, but the other team does not.<br /> 49 if ((numFinishers >= TIE_BREAKER_PLACE) && (o.numFinishers < TIE_BREAKER_PLACE)) return -1;<br /> 50<br /> 51 // Both teams have a 6th place finisher.<br /> 52 if ((numFinishers >= TIE_BREAKER_PLACE) && (o.numFinishers >= TIE_BREAKER_PLACE))<br /> 53 return new Integer(tieBreaker).compareTo(o.tieBreaker);<br /> 54<br /> 55 // Neither team has a 6th place finisher.<br /> 56 return new Character(name).compareTo(o.name);<br /> 57<br /> 58 }<br /> 59 }<br /> 60<br /> 61<br /> 62 public String scoreMeet(int numTeams, String finishOrder) {<br /> 63<br /> 64 Team[] teams = new Team[numTeams];<br /> 65<br /> 66 // Initialize an ArrayList with a Team object for each team.<br /> 67 char name = 'A';<br /> 68 for (int i = 0; i < numTeams; i++) {<br /> 69 teams[i] = (new Team(name++));<br /> 70 }<br /> 71<br /> 72 int score = 1;<br /> 73<br /> 74 /*<br /> 75 * Work left to right through the finishOrder string. For each<br /> 76 * character, determine corresponding team by subtracting the value<br /> 77 * of 'A' from the character to get it's index in the teams list.<br /> 78 */<br /> 79 for (int i = 0; i < finishOrder.length(); i++) {<br /> 80 char c = finishOrder.charAt(i);<br /> 81 teams[c - 'A'].addFinisher(score++);<br /> 82 }<br /> 83<br /> 84 // Holds only those teams with 5 or more finishers.<br /> 85 List<Team> qualifyingTeams = new ArrayList<>();<br /> 86<br /> 87 for (int i = 0; i < teams.length; i++) {<br /> 88 if (teams[i].numFinishers >= MIN_FINISHERS) {<br /> 89 qualifyingTeams.add(teams[i]);<br /> 90 }<br /> 91 }<br /> 92<br /> 93 // Use the Team.compareTo() method to sort the teams out.<br /> 94 Collections.sort(qualifyingTeams);<br /> 95<br /> 96 /*<br /> 97 * Build our return string by going through the sorted list<br /> 98 * and adding the team names.<br /> 99 */<br /> 100 StringBuilder sb = new StringBuilder(qualifyingTeams.size());<br /> 101<br /> 102 for (Team t : qualifyingTeams) {<br /> 103 sb.append(t.name);<br /> 104 }<br /> 105<br /> 106 return sb.toString();<br /> 107 }<br /> 108 }<br /></pre> </div> <div class="header">Notes:</div> <p> I've created a class Team the implements Comparable so that we can use Java's built-in sort capabilities. All the logic necessary for sorting the teams is contained in the Team.compareTo() method. </p> <p> With that, it's just a matter of creating the team objects, and adding their finishing places. Lines 67-70 create an array of teams and assign each one it's name. Then the loop on lines 79-82 works through each of the letters in finishOrder and calls addFinisher() on the corresponding team. We can get the correct team by subtracting 'A' from the current letter. For example, if the letter is 'C', the 'C' - 'A' = 2, which is the position in the teams array of team C. </p> <p> The addFinisher() method handles the logic of determining if this runner's score counts toward the team's score (it's a top 5 runner), or if we should store this score in tieBreaker (if it's the 6th runner for that team). </p> <p> Once all the team data is populated, we add only those teams with 5 or more runners to the qualifyingTeams list, sort the list, and then add each team's name in order to the string that we return. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-82251273240703530172015-07-15T18:21:00.003-04:002015-07-15T20:51:33.068-04:00RPG<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1944" target="_blank">TopCoder Problem Statement - RPG</a> </td> </tr> <tr><td>Single Round Match 171 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine the minimum, maximum, and average for a set of dice rolls. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class RPG {<br /> 2<br /> 3 public int[] dieRolls(String[] dice) {<br /> 4<br /> 5 int min = 0;<br /> 6 int max = 0;<br /> 7<br /> 8 for (int d = 0; d < dice.length; d++) {<br /> 9<br /> 10 /*<br /> 11 * Splits the string into the parts before and after the 'd'<br /> 12 */<br /> 13 String[] s = dice[d].split("d");<br /> 14<br /> 15 int rolls = Integer.parseInt(s[0]);<br /> 16 int die = Integer.parseInt(s[1]);<br /> 17<br /> 18 min += rolls;<br /> 19 max += (rolls * die);<br /> 20 }<br /> 21<br /> 22 int average = ((max - min) / 2) + min;<br /> 23<br /> 24 return new int[] {min, max, average};<br /> 25 }<br /> 26<br /> 27<br /> 28 }<br /></pre> </div> <div class="header">Notes:</div> <p> The first task is to parse each string in the array to get the size of the die and the number of rolls. This is easy enough using String.split(). By splitting on the "d" character, we'll get the number of rolls in position 0, and the size of the die in position 1 or the resulting array. </p> <p> To get the minimum value, we just assume that the die always comes up one. So, minimum is just equal to the number of die rolls. </p> <p> To get the maximum value, we assume that die always comes up with it's largest possible value. Here, we just multiple the number of rolls by the size of the die. </p> <p> Then, we compute the average using the formula on line 22. </p> <p> We these three values calculate, we just create an int[] to hold them, and return it. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-38998853887463427512015-05-22T16:01:00.002-04:002015-05-22T16:01:35.785-04:00MutaliskEasy<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=13782" target="_blank">TopCoder Problem Statement - MutaliskEasy</a> </td> </tr> <tr><td>Single Round Match 658 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Given attacks that do 9,3, and 1 point of damage, determine the fewest number of rounds needed to take out an opponent. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class MutaliskEasy {<br /> 2<br /> 3 private static final int[] ATTACKS = {9, 3, 1};<br /> 4 private static final int MAX_HP = 60;<br /> 5<br /> 6 int[][][] results = new int[MAX_HP + 1][MAX_HP + 1][MAX_HP + 1];<br /> 7<br /> 8 public int minimalAttacks(int[] x) {<br /> 9<br /> 10 // Nothing to do.<br /> 11 if (x.length == 0) return 0;<br /> 12<br /> 13 // Just divide by the maximum attack value.<br /> 14 if (x.length == 1) {<br /> 15 if (x[0] % ATTACKS[0] == 0) {<br /> 16 return x[0] / ATTACKS[0];<br /> 17 } else {<br /> 18 return x[0] / ATTACKS[0] + 1;<br /> 19 }<br /> 20 }<br /> 21<br /> 22 /*<br /> 23 * The problem does not fall into one of the easy cases,<br /> 24 * so we'll have to do some work...<br /> 25 */<br /> 26<br /> 27 // Initialize results.<br /> 28 for (int i = 0; i <= MAX_HP; i++) {<br /> 29 for (int j = 0; j <= MAX_HP; j++) {<br /> 30 for (int k = 0; k <= MAX_HP; k++) {<br /> 31 results[i][j][k] = -1;<br /> 32 }<br /> 33 }<br /> 34 }<br /> 35 results[0][0][0] = 0;<br /> 36<br /> 37 /*<br /> 38 * We'll treat a length of 2 the same as if it had 3. Just<br /> 39 * give the 3rd element a value of 0.<br /> 40 */<br /> 41 if (x.length == 2) return minimalAttacks(x[0], x[1], 0);<br /> 42 if (x.length == 3) return minimalAttacks(x[0], x[1], x[2]);<br /> 43<br /> 44 return -1; // Length of x must be >= 0 and <= 3<br /> 45<br /> 46 }<br /> 47<br /> 48 private int minimalAttacks(int x, int y, int z) {<br /> 49<br /> 50 // Don't allow values to go below 0.<br /> 51 if (x < 0) x = 0;<br /> 52 if (y < 0) y = 0;<br /> 53 if (z < 0) z = 0;<br /> 54<br /> 55<br /> 56 // If we've already calculated this result, just return it.<br /> 57 if (results[x][y][z] >= 0) return results[x][y][z];<br /> 58<br /> 59 int minAttacks = Integer.MAX_VALUE;<br /> 60<br /> 61 // Try all possible combinations.<br /> 62 for (int i = 0; i < ATTACKS.length; i++) {<br /> 63<br /> 64 for (int j = 0; j < ATTACKS.length; j++) {<br /> 65 if (j == i) continue;<br /> 66<br /> 67 for (int k = 0; k < ATTACKS.length; k++) {<br /> 68 if ((k == i) || (k == j)) continue;<br /> 69<br /> 70 minAttacks = Math.min(minAttacks,<br /> 71 minimalAttacks(<br /> 72 x - ATTACKS[i],<br /> 73 y - ATTACKS[j],<br /> 74 z - ATTACKS[k]));<br /> 75 }<br /> 76 }<br /> 77 }<br /> 78<br /> 79 results[x][y][z] = minAttacks + 1;<br /> 80 return minAttacks + 1;<br /> 81<br /> 82 }<br /> 83<br /> 84 }<br /></pre> </div> <div class="header">Notes:</div> <p> My first approach was a simple greedy algorithm. I sorted the opponents according to the amount of hit points they had remaining, and then assigned the biggest attack to the opponent with most hit points remaining, the next biggest attack to the next strongest opponent, and the last attack to the third strongest opponent. Then I re-sorted the opponents, and repeated. As the first test shows, this approach does not work. </p> <p> Instead, we'll need to try every possible combination. </p> <p> The minimalAttacks(int,int,int) method begins by ensuring we don't allow the hit point values to go below 0. Then it checks to see if we've already solved for this combination of x, y, and z. If so, then we can just return that value This technique is called memoization, and allows up to skip the calculations that follow if they've already been carried out. </p> <p> If we don't already have a result, then the loops on lines 62-77 will recursively call minimalAttacks with every possible combination of assigning attacks to the various opponents. We keep track of the best result in the minAttacks variable, and then store this in the results matrix before returning it. </p> <p> The minimalAttacks(int[]) method checks for a few easy cases (length of x is 0 or 1), and failing that initializes the results matrix, and then uses minimalAttacks(int, int, int) to calculate the result. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-16675435097497796052015-05-22T15:59:00.000-04:002015-05-22T15:59:08.295-04:00InfiniteString<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=13783" target="_blank">TopCoder Problem Statement - InfiniteString</a> </td> </tr> <tr><td>Single Round Match 658 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine if two strings, when repeated infinitely, are equal. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class InfiniteString {<br /> 2<br /> 3 public String equal(String s, String t) {<br /> 4<br /> 5 int ptrS = 0;<br /> 6 int ptrT = 0;<br /> 7<br /> 8 /*<br /> 9 * Continue looping one character at a time until<br /> 10 * we reach both the end of String s and the end<br /> 11 * of String t at the same time.<br /> 12 */<br /> 13 while ((ptrS < s.length()) || (ptrT < t.length())) {<br /> 14<br /> 15 /*<br /> 16 * If at the end of a String, start over at<br /> 17 * the beginning.<br /> 18 */<br /> 19 ptrS %= s.length();<br /> 20 ptrT %= t.length();<br /> 21<br /> 22 // Return "Not Equal" if characters do not match<br /> 23 if (s.charAt(ptrS) != t.charAt(ptrT)) return "Not equal";<br /> 24<br /> 25 ptrS++;<br /> 26 ptrT++;<br /> 27 }<br /> 28<br /> 29 return "Equal";<br /> 30 }<br /> 31 }<br /></pre> </div> <div class="header">Notes:</div> <p> Imagine creating two Strings s1 and t1 such that s1 = s + s + s ... and t1 = t + t + t + t + ... and the length of both s1 and t1 is equal to the least common multiple of the lengths of s and t. </p> <p> For example if s = "ababab" and t = "abab", then the length of s is 6, the length of t is 4, and their least common multiple is 12. Therefore, s1 = s + s = "abababababab" and t1 = t + t + t = "abababababab". Since s1 == t1 we should return "Equal" </p> <p> The important point is that if we step through the Strings s and t one character at a time, and loop back to the beginning of the String when we reach the end; then we can stop when we reach the end of both s and t at the same time. That's the condition that is checked for in the while loop. </p> <p> The rest is just a matter of checking that the characters match at each position, and incrementing and resetting the pointer to the current character. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-79493644926275317302015-05-16T22:43:00.001-04:002015-05-16T22:43:13.324-04:00Poetry<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1835" target="_blank">TopCoder Problem Statement - Poetry</a> </td> </tr> <tr><td>Single Round Match 170 Round 1 - Division II, Level Three</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine the rhyme scheme of a poem. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 import java.util.HashMap;<br /> 2 import java.util.Map;<br /> 3<br /> 4 public class Poetry {<br /> 5<br /> 6 public String rhymeScheme(String[] poem) {<br /> 7<br /> 8 // The label we'll assign to the next rhyme.<br /> 9 char nextRhymeLabel = 'a';<br /> 10<br /> 11 /*<br /> 12 * We'll fill in this array as we go, and ultimately<br /> 13 * return it.<br /> 14 */<br /> 15 char[] result = new char[poem.length];<br /> 16<br /> 17 // Maps and ending sound to a label.<br /> 18 Map<String, Character> endings = new HashMap<>();<br /> 19<br /> 20<br /> 21 for (int line = 0; line < poem.length; line++) {<br /> 22<br /> 23 // Split the line on whitespace characters<br /> 24 String[] words = poem[line].trim().split("\\s+");<br /> 25<br /> 26 /*<br /> 27 * If the line was empty (or just spaces), words will<br /> 28 * have a length of 1, and the only entry will have<br /> 29 * a length of 0.<br /> 30 */<br /> 31 if ((words.length == 1) && (words[0].length() == 0)) {<br /> 32 result[line] = ' ';<br /> 33<br /> 34 } else {<br /> 35<br /> 36 String lastWord = words[words.length - 1];<br /> 37 String ending = getWordEnding(lastWord.toLowerCase());<br /> 38<br /> 39 if (endings.containsKey(ending)) {<br /> 40<br /> 41 /*<br /> 42 * We've already seen this ending, so just<br /> 43 * look up the label.<br /> 44 */<br /> 45 result[line] = endings.get(ending);<br /> 46<br /> 47 } else {<br /> 48<br /> 49 /*<br /> 50 * This is a new ending, so store<br /> 51 * it, and increment to the next label.<br /> 52 */<br /> 53 endings.put(ending, nextRhymeLabel);<br /> 54 result[line] = nextRhymeLabel;<br /> 55<br /> 56 if (nextRhymeLabel == 'z') {<br /> 57 nextRhymeLabel = 'A';<br /> 58 } else {<br /> 59 nextRhymeLabel += 1;<br /> 60 }<br /> 61 }<br /> 62 }<br /> 63 }<br /> 64<br /> 65 return new String(result);<br /> 66<br /> 67 }<br /> 68<br /> 69 private String getWordEnding(String word) {<br /> 70<br /> 71 int i = word.length() - 1;<br /> 72<br /> 73 // Work backward until we reach the first vowel.<br /> 74 while ((i >= 0) && (!isVowel(word.charAt(i), i, word.length()))) {<br /> 75 i--;<br /> 76 }<br /> 77<br /> 78 /*<br /> 79 * Continue so long as it remains a vowel. Don't<br /> 80 * go past the beginning of the word.<br /> 81 */<br /> 82 while ((i >= 0) && (isVowel(word.charAt(i), i, word.length()))) {<br /> 83 i--;<br /> 84 }<br /> 85<br /> 86 // Return the ending of word starting at position i+1<br /> 87 return word.substring(i+1);<br /> 88<br /> 89<br /> 90 }<br /> 91<br /> 92 /*<br /> 93 * Returns true if c is one of: a, e, i, o, or u.<br /> 94 * Also returns true if c is y and not the first or last<br /> 95 * letter of the word. Otherwise, returns false.<br /> 96 */<br /> 97 private boolean isVowel(char c, int position, int wordLength) {<br /> 98<br /> 99 if ((c == 'a') ||<br /> 100 (c == 'e') ||<br /> 101 (c == 'i') ||<br /> 102 (c == 'o') ||<br /> 103 (c == 'u')) return true;<br /> 104<br /> 105 if ((c == 'y') &&<br /> 106 ((position != 0) && (position != (wordLength - 1)))) return true;<br /> 107<br /> 108 return false;<br /> 109<br /> 110 }<br /> 111 }<br /></pre> </div> <div class="header">Notes:</div> <p> Easier than the 500 point solution <a href="/2015/05/recurrencerelation.html">RecurrenceRelation</a>, Poetry is pretty straight forward. There's just three things to take care of: </p> <p> First, we need to split each line of the input up into words, and then examine the last word of the line. Splitting it up is easy with the String.split() method, using the "\\s+" regular expression. Then we need to check to make sure it wasn't an empty line. The word we're interested in is the last element of the result of the split. </p> <p> Next we need to determine the ending of the word. For this, we start at the end of the word and work backward until we reach the first vowel. Then we continue backward so long as we continue getting vowels, and we don't run past the beginning of the String. </p> <p> Finally, we need a method to determine if a character is a vowel. This is trivial for characters other than 'y'. 'y' is a vowel unless it is the first or last character of the word. </p> <p> With that in place, the rest is just housekeeping. We create a char[] named result to hold the label for each line. nextRhymeLabel holds the character we'll use for the next previously unseen word ending. When a new ending is encountered, we assign it the value in nextRhymeLabel, and then increment nextRhymeLabel, or set it to 'A' if it has reached 'z'. We use a HashMap to map endings that we've seen to the labels that were assigned to them. </p> <p> There's really nothing difficult about this problem. I'm really surprised that it was not just Division 2 - 500 points. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-90622490161229951822015-05-16T22:42:00.001-04:002015-05-16T22:42:04.916-04:00RecurrenceRelation<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1915" target="_blank">TopCoder Problem Statement - RecurrenceRelation</a> </td> </tr> <tr><td>Single Round Match 170 Round 1 - Division I, Level One</td></tr> <tr><td>Single Round Match 170 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Solve for the value of X[n] where X[n] is based on X[n-1], X[n-2], ... </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class RecurrenceRelation {<br /> 2<br /> 3 public int moduloTen(int[] coefficients, int[] initial, int N) {<br /> 4<br /> 5 int K = coefficients.length;<br /> 6<br /> 7 /*<br /> 8 * Stores the solution to the previous K problems.<br /> 9 */<br /> 10 int[] X = new int[K];<br /> 11<br /> 12 /*<br /> 13 * Initialize X to contain the values given<br /> 14 * in initial. We need to mod these first.<br /> 15 */<br /> 16 for (int i = 0; i < X.length; i++) {<br /> 17 X[i] = myMod(initial[i], 10);<br /> 18 }<br /> 19<br /> 20 // If we already have the answer, just return it.<br /> 21 if (N < K) return X[N];<br /> 22<br /> 23 int n = K;<br /> 24<br /> 25 while (n <= N) {<br /> 26<br /> 27 /*<br /> 28 * Add up the previous K solutions.<br /> 29 */<br /> 30 int sum = 0;<br /> 31<br /> 32 for (int k = 0; k < K; k++) {<br /> 33 sum += coefficients[k] * X[k];<br /> 34 }<br /> 35<br /> 36 sum = myMod(sum, 10);<br /> 37<br /> 38 /*<br /> 39 * We have our answer, so shuffle everything down to<br /> 40 * make room for it - dropping the olds solution off<br /> 41 * since we won't need it any more.<br /> 42 */<br /> 43<br /> 44 for (int i = 0; i < (K - 1); i++) {<br /> 45 X[i] = X[i + 1];<br /> 46 }<br /> 47<br /> 48 // Insert the current solution into the end of the array.<br /> 49 X[K - 1] = sum;<br /> 50<br /> 51 // Start working on the next solution.<br /> 52 n++;<br /> 53 }<br /> 54<br /> 55 // Return the most recently solved.<br /> 56 return X[K - 1];<br /> 57 }<br /> 58<br /> 59 /*<br /> 60 * This handles mod'ing negative numbers, and is taken<br /> 61 * straight out of the problem definition.<br /> 62 */<br /> 63 private static int myMod(int i, int m) {<br /> 64<br /> 65 if (i >= 0) return i % m;<br /> 66<br /> 67 return ((m - ((-1 * i) % m)) % m);<br /> 68 }<br /> 69 }<br /><br /></pre> </div> <div class="header">Notes:</div> <p> The wording of this problem makes it sound much more difficult than it actually is. You may need to read the description several times in order to understand what it's getting at. Basically, you're asked to solve for the value of X[n], where X[n] is based on the values of X[n-1], X[n-2], etc. The number of previous elements that combine to create the value of X[n] is K, where K is the length of both the coefficients and initial arrays. </p> <p> Start by creating an array of ints, X[], to hold these values. Then we initialize X[] using the values from initial[]. Note that we need to perform the mod operation as described int the problem statement before inserting any value into X[]. Also note that if the number we're being asked to solve for (N) is less than, or equal to, the length of the initial[] array (N <= K), then we already have our answer. We can just return the the value in X[N]. </p> <p> Otherwise, we need to solve for each value of X[n] up to n = N. To get the next value we multiply each value in X[] by it's corresponding value in coefficients[] and note their sum. Then we shift all elements in X[] down by 1 (dropping off the value in X[0]) and insert our new value into the right-most position - after running it through the mod operation. </p> <p> Once n == N, we have solved for the number that was asked for. The value we need is the most recent solution found which is stored in the greatest element of X. </p> <p> The method myMod() simply implements the mod function as described in the problem statement. It is the normal % function, modified to handle negative numbers. </p> <p> Again, the toughest part of the problem is just reading through the problem statement making sense of it. I actually thought this was harder than the 1000 point problem <a href="/2015/05/poetry.html">Poetry</a>. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-24781034063192823832015-05-16T22:40:00.002-04:002015-05-16T22:40:41.923-04:00LevelUp<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1930" target="_blank">TopCoder Problem Statement - LevelUp</a> </td> </tr> <tr><td>Single Round Match 170 Round 1 - Division II, Level One</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine the number of experience point a character needs in order to reach the next level. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class LevelUp {<br /> 2<br /> 3 public int toNextLevel(int[] expNeeded, int received) {<br /> 4<br /> 5 int i = 0;<br /> 6<br /> 7 /*<br /> 8 * Find the first expNeeded element that is greater<br /> 9 * than received.<br /> 10 */<br /> 11 while (expNeeded[i] <= received) i++;<br /> 12<br /> 13 /*<br /> 14 * Return the difference between the next level, and<br /> 15 * the amount received.<br /> 16 */<br /> 17 return (expNeeded[i] - received);<br /> 18<br /> 19 }<br /> 20 }</pre> </div> <div class="header">Notes:</div><p> Certainly one of the easiest problems to solve. Just loop through the values in expNeeded until you find one that is greater than received. Then just return that next value minus the amount of received. </p> <p> Really the only thing to be careful of is the case where the amount received exactly equals the amount needed for a level. In this case, return the amount needed to reach the next level, and not 0. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-18419561023489778482015-05-12T17:49:00.002-04:002015-05-12T17:49:34.469-04:00FairWorkload<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1901" target="_blank">TopCoder Problem Statement - FairWorkload</a> </td> </tr> <tr><td>Single Round Match 169 Round 1 - Division I, Level Two</td></tr> <tr><td>Single Round Match 169 Round 1 - Division II, Level Three</td></tr> </table> </p> <div class="header">Overview:</div> <p> Determine the minimum time needed to search through a set of folders given a number of workers. The workers must search a contiguous set of folders, and each folder may take a varying amount of time to process. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class FairWorkload {<br /> 2<br /> 3 public int getMostWork(int[] folders, int workers) {<br /> 4<br /> 5 /*<br /> 6 * Stores the best time that we can complete a given<br /> 7 * number of folders with a given number workers.<br /> 8 */<br /> 9 int[][] times = new int[workers][folders.length];<br /> 10<br /> 11 /*<br /> 12 * With just 1 worker, the completion time<br /> 13 * of folder f will be the sum of the times<br /> 14 * it takes to process each folder up to and<br /> 15 * including f.<br /> 16 */<br /> 17 for (int f = 0; f < folders.length; f++) {<br /> 18 times[0][f] = sumSections(0, f+1, folders);<br /> 19 }<br /> 20<br /> 21 for (int w = 1; w < workers; w++) {<br /> 22 for (int f = 0; f < folders.length; f++) {<br /> 23<br /> 24 // Cannot have less folders than workers<br /> 25 if (f < w) {<br /> 26 times[w][f] = -1;<br /> 27<br /> 28 } else {<br /> 29<br /> 30 int minCompletionTime = Integer.MAX_VALUE;<br /> 31<br /> 32 /*<br /> 33 * Try all combinations of splitting the<br /> 34 * folders between previous workers and<br /> 35 * the current worker. d - marks<br /> 36 * the division point, where the current<br /> 37 * worker begins.<br /> 38 */<br /> 39 for (int d = w; d <= f; d++) {<br /> 40<br /> 41 int completionTime = Math.max(<br /> 42 times[w-1][d-1],<br /> 43 sumSections(d, f+1, folders));<br /> 44<br /> 45 minCompletionTime = Math.min(<br /> 46 minCompletionTime,<br /> 47 completionTime);<br /> 48 }<br /> 49<br /> 50 times[w][f] = minCompletionTime;<br /> 51 }<br /> 52 }<br /> 53 }<br /> 54<br /> 55 return times[workers - 1][folders.length - 1];<br /> 56 }<br /> 57<br /> 58 /*<br /> 59 * Return the sum of the elements in the nums array<br /> 60 * starting at s and stopping just before e.<br /> 61 */<br /> 62 private int sumSections(int s, int e, int[] nums) {<br /> 63 int sum = 0;<br /> 64<br /> 65 for (int x = s; x < e; x++) {<br /> 66 sum += nums[x];<br /> 67 }<br /> 68<br /> 69 return sum;<br /> 70 }<br /> 71<br /> 72 }<br /></pre> </div> <div class="header">Notes:</div> <p> FairWorkload is a problem that begs for a dynamic programming solution. To solve this, we'll build up a table that holds the best finishing time we can achieve given a number of workers and a number of folders. We'll start with the trivial case of just one worker. Using that information, we'll add additional workers and folders until we've completed the table. The result will be the table shown below. With that, we can just return the value of the cell in the bottom right corner. </p> <p> Don't be confused by the number of workers; I've labeled the table using its indexes, so "Workers 0" is the case with one worker. Same goes for folders across the top. </p> <p> The table is initialized by filling in the top row. With just one worker, the number of sections searched is just the sum of the sections in all previous folders, plus the number of sections in the current folder. This could have been done more efficiently by keeping a running total of the number of sections, but since I needed a sumSections() method anyway, I chose to rely on that here. </p> <p> Note that we cannot satisfy the constraints of the problem if there are fewer folders than their are workers. These cases are noted with a -1, although that never really comes into play. </p> <p> Things begin to get interesting with the second worker. With 2 workers and 2 folders, we know that 1 worker must look through 10 sections to complete 1 folder, and that worker 2 must look through 20 sections to complete the next folder. Therefore the minimum number of sections is 20. </p> <p> With 2 workers and three folders we have a choice in how to complete the task. We can either assign the first 2 folders to worker 1, and the third to worker 2 (scenario 1)- or we can assign just the first folder to worker 1, and the remaining two to worker 2 (scenario 2). We need to check both cases and see with gives the better result. Scenario 1 gives 10 + 20 = 30 sections to worker 1 and 30 sections to worker 2. Scenario 2 gives 10 sections to worker 1 and 20 + 30 = 50 sections to worker 2. The max of 30 in scenario 1 is better than the max of 50 in scenario 2, so 30 is our value here. </p> <p> The loop on line 39 works through each scenario. In general, we want to minimize the maximum value of sections as we move the dividing line across the range of folders. The dividing line separates the work done by previous workers on one side (which can be pulled right out of the table), and the work done by the latest worker, which is the sum of the number of sections remaining. </p> <table border="2"> <tr> <td /> <td colspan="9">Folder / Number of Sections</td> </tr> <tr> <td/> <td>0/10</td> <td>1/20</td> <td>2/30</td> <td>3/40</td> <td>4/50</td> <td>5/60</td> <td>6/70</td> <td>7/80</td> <td>8/90</td> </tr> <tr> <td>Workers<br/>0</td> <td>10</td> <td>30</td> <td>60</td> <td>100</td> <td>150</td> <td>210</td> <td>280</td> <td>360</td> <td>450</td> </tr> <tr> <td>1</td> <td>-1</td> <td>20</td> <td>30</td> <td>60</td> <td>90</td> <td>110</td> <td>150</td> <td>210</td> <td>240</td> </tr> <tr> <td>2</td> <td>-1</td> <td>-1</td> <td>30</td> <td>40</td> <td>60</td> <td>90</td> <td>110</td> <td>150</td> <td>170</td> </tr> <tr> <td>3</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>40</td> <td>50</td> <td>60</td> <td>90</td> <td>110</td> <td>150</td> </tr> <tr> <td>4</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>50</td> <td>60</td> <td>70</td> <td>90</td> <td>110</td> </tr> </table> <p> This is a great problem to hone you dynamic programming skills. Please take the time to make sure that you understand what's going on. It's a great tool to have for many TopCoder problems. </p> <p> To help make it as clear as I can, let me walk through the final cell. Imagine that the bottom right cell was not yet filled in. From the previous row, we know the best solutions for each number of folders with one less worker. Since each worker must have at least one folder, we can divide the 9 folders up as follows: </p> <p> Folders 0 - 3 processed by workers 0 - 3 / Folders 4 - 8 processed by Worker 4. From the table, we know the previous workers would have a max of 40 sections. But this leaves 50 + 60 + 70 + 80 + 90 = 350 sections for the last worker. </p> <p> We then try... </p> <p> Folders 0 - 4 processed by workers 0 - 3 / Folders 5 - 8 processed by Worker 4. Again from the table, the previous workers can do folders 0 - 4 with a max of 50. Worker 4 has 60 + 70 + 80 + 90 = 300 sections. Better than before, but still not the best we can do. </p> <p> Folders 0 - 5 processed by workers 0 - 3 / Folders 6 - 8 processed by Worker 4. The previous workers have a max of 60, and Worker 4 has 70 + 80 + 90 = 240. Better still. </p> <p> Folders 0 - 6 processed by workers 0 - 3 / Folders 7 - 8 processed by Worker 4. The previous workers now have a max of 90, and Worker 5 has 80 + 90 = 170. </p> <p> It turns out the best solution is to have Folders 0 - 7 processed by workers 0 - 3 / and just Folder 8 processed by worker 4. The previous workers have a max of 110 sections, and Worker 4 has just 90 sections. The max of 110 is the best we can do, so that's what goes into the bottom right cell. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0tag:blogger.com,1999:blog-4579874619428156854.post-1963887529581687402015-05-12T17:47:00.004-04:002015-05-12T17:47:47.561-04:00Twain<div class="solution"> <div class="header">Problem:</div> <p> <table> <tr> <td> <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1867" target="_blank">TopCoder Problem Statement - Twain</a> </td> </tr> <tr><td>Single Round Match 169 Round 1 - Division II, Level Two</td></tr> </table> </p> <div class="header">Overview:</div> <p> Perform a series of manipulations to a String and return the result. </p> <div class="header">Java Source:</div> <div class="code"><pre><br /> 1 public class Twain {<br /> 2 <br /> 3 public String getNewSpelling(int year, String phrase) {<br /> 4 <br /> 5 if (year >= 1) {<br /> 6 // If a word starts with x, replace it with a z<br /> 7 phrase = phrase.replaceAll("\\bx","z");<br /> 8 <br /> 9 phrase = phrase.replaceAll("x","ks");<br /> 10 }<br /> 11 <br /> 12 if (year >= 2) {<br /> 13 phrase = phrase.replaceAll("y", "i");<br /> 14 }<br /> 15 <br /> 16 if (year >= 3) {<br /> 17 /*<br /> 18 * If a 'c' is followed immediately by an 'e' or<br /> 19 * an 'i', then replace the 'c' with an 's'.<br /> 20 */<br /> 21 phrase = phrase.replaceAll("c([ei])", "s$1");<br /> 22 }<br /> 23 <br /> 24 if (year >= 4) {<br /> 25 <br /> 26 /*<br /> 27 * Remove repeating 'c's that end with a 'k'<br /> 28 * with just a 'k'.<br /> 29 */<br /> 30 phrase = phrase.replaceAll("c+k", "k");<br /> 31 }<br /> 32 <br /> 33 if (year >= 5) {<br /> 34 <br /> 35 /*<br /> 36 * Replace 'sch' at the beginning of a word with<br /> 37 * 'sk'<br /> 38 */<br /> 39 phrase = phrase.replaceAll("\\bsch", "sk");<br /> 40 <br /> 41 phrase = phrase.replaceAll("chr", "kr");<br /> 42 <br /> 43 /*<br /> 44 * Replace all 'c' s that are not followed immediately<br /> 45 * by a 'h' with a 'k'<br /> 46 */<br /> 47 phrase = phrase.replaceAll("c(?!h)", "k");<br /> 48 <br /> 49 }<br /> 50 <br /> 51 if (year >= 6) {<br /> 52 <br /> 53 /*<br /> 54 * Replace all words that start with 'kn'<br /> 55 * with just 'n'<br /> 56 */<br /> 57 phrase = phrase.replaceAll("\\bkn", "n");<br /> 58 }<br /> 59 <br /> 60 if (year >= 7) {<br /> 61 <br /> 62 /*<br /> 63 * Replace all repeating consonants, with just the<br /> 64 * single character.<br /> 65 */<br /> 66 phrase = phrase.replaceAll("([b-df-hj-np-tv-z])\\1+", "$1");<br /> 67 }<br /> 68 <br /> 69 return phrase;<br /> 70 }<br /> 71 }<br /></pre> </div> <div class="header">Notes:</div> <p> It looks like a lot of coders had a tough time with this problem. The solution given <a href="http://community.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm169" target="_blank">here</a> seems like a lot of work. Fortunately, if you're up on your regular expressions, you can knock this out easily. If you're rusty with regular expressions, this is a great opportunity to exercise these important skills. </p> <p>The first rule under year one uses the \\b character which matches with the start of a word boundary. \\bx matches any x at the start of a word. The second rule trivially replaces all remaining occurrences of "x" with "ks". </p> <p>Year two is also trivial. we simply replace all occurrences of letter "y" with an "i". Nothing difficult there. </p> <p>The rule for year three is a little more difficult. We need to replace any "c" followed immediately by an "e" or "i" with an "s". The rule "c([ei])" matches on the "c" followed by either an "e" or an "i". By putting the parenthesis around "[ei]" the value it matches is stored in a variable. We access the variable with $1. The result "s$1" replaces the "c" with an "s" and then tacks on whatever the "[ei]" matched. </p> <p>The rule for year four simply replaces 1 or more occurrences of the letter "c" ending with a "k" with just a "k". </p> <p>We've already seen the first two rules for year 5. The final rule is a bit tricky. It matches a "c" that is not immediately followed by an "h" with a "k". </p> <p>The rule for year six is basically the same as that the first rule of year 1. </p> <p>The rule for year seven is probably the most difficult. All consonants are defined by the ranges contained within the square brackets. Note that the vowels are missing here. The group is also enclosed within parenthesis, so we can refer to what it matches later using the variable $1. The \\1+ means that we want to match any occurrence of 1 or more consonants. We then replace this with just the single consonant. </p> <p>I hope this gives some idea of how simple the problem can be solved using regular expressions. My goal is not to give an precise definition for any of the constructs used above, but rather just to show you how they could be used in this example. </p> <div class="footer"> <p><i>Thank you</i> for taking the time to read this solution. I welcome any feedback you may have.</p> <p> All Solutions and descriptions are now available on GitHub at <a href="https://github.com/pmonkelban/TopCodingSolutions">https://github.com/pmonkelban/TopCodingSolutions</a> </p> </div></div>Anonymoushttp://www.blogger.com/profile/10778107116578137666noreply@blogger.com0