Skip to content

Commit 53bf03b

Browse files
committed
CardGameOne
1 parent b33c32b commit 53bf03b

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package codechallenges.dynamicprogramming;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* CardGameOne
7+
*
8+
* YetAnotherCardGame @see
9+
*
10+
* http://community.topcoder.com/stat?c=problem_statement&pm=13912
11+
*
12+
*/
13+
public class CardGameOne {
14+
15+
public int[] solve(int[] cards1, int[] cards2) {
16+
17+
int pileIndex = 0;
18+
int pileCard = 0;
19+
int[] pile = new int[cards1.length + cards2.length];
20+
pile[pileIndex] = 0;
21+
22+
Arrays.sort(cards1);
23+
Arrays.sort(cards2);
24+
25+
for (int i = 0; i < cards1.length; i++) {
26+
27+
for (int j = i; j < cards1.length; j++) {
28+
29+
if (cards1[j] > pileCard) {
30+
pileCard = pile[pileIndex] = cards1[j];
31+
pileIndex += 1;
32+
break;
33+
}
34+
}
35+
36+
for (int j = 0; j < cards2.length; j++) {
37+
38+
if (cards2[j] > pileCard) {
39+
pileCard = pile[pileIndex] = cards2[j];
40+
pileIndex += 1;
41+
break;
42+
}
43+
}
44+
}
45+
46+
return Arrays.copyOf(pile, pileIndex);
47+
}
48+
49+
public static void main(String[] args) {
50+
CardGameOne solver = new CardGameOne();
51+
int[] cards1 = new int[]{2, 5};
52+
int[] cards2 = new int[]{3, 1};
53+
int[] pile = solver.solve(cards1, cards2);
54+
System.out.println("Pile: " + Arrays.toString(pile) + ", count: " + pile.length);
55+
}
56+
57+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package codechallenges.dynamicprogramming;
2+
3+
import java.util.Arrays;
4+
import java.util.Collection;
5+
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.junit.runners.Parameterized;
9+
10+
import static org.junit.Assert.assertArrayEquals;
11+
12+
/**
13+
* CardGameOne test class
14+
*/
15+
@RunWith(Parameterized.class)
16+
public class CardGameOneTest {
17+
18+
int[] cards1;
19+
int[] cards2;
20+
int[] expected;
21+
22+
public CardGameOneTest(int[] cards1, int[] cards2, int[] expected) {
23+
this.cards1 = cards1;
24+
this.cards2 = cards2;
25+
this.expected = expected;
26+
}
27+
28+
@Parameterized.Parameters
29+
public static Collection<int[][]> parameters() {
30+
int[][][] params = new int[][][]{
31+
{{2, 5}, {3, 1}, {2, 3, 5}},
32+
{{1, 1, 1, 1, 1}, {1, 1, 1, 1, 1}, {1}},
33+
{{1, 4, 6, 7, 3}, {1, 7, 1, 5, 7}, {1, 5, 6, 7}}
34+
};
35+
return Arrays.asList(params);
36+
}
37+
38+
@Test
39+
public void shouldFindExpectedLongestSequences() {
40+
CardGameOne solver = new CardGameOne();
41+
assertArrayEquals(expected, solver.solve(cards1, cards2));
42+
}
43+
44+
}

0 commit comments

Comments
 (0)