Skip to content

Commit 96f9a8f

Browse files
committed
DFS_performStep. Implement perform step, fix Pizza toString, fix cutStartPositions
1 parent 2011e29 commit 96f9a8f

File tree

5 files changed

+51
-77
lines changed

5 files changed

+51
-77
lines changed

src/main/java/com/google/hashcode/entity/Pizza.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,8 @@ public List<Cell> getCells() {
3737
* @param x - column number,0..max column number
3838
* @return a pizza cell with specified coordinated
3939
*/
40-
public Cell getCell(int y, int x) {
41-
final Optional<Cell> cellByCoordinates = cells.stream().filter(cell -> cell.x == x && cell.y == y).findFirst();
42-
if (cellByCoordinates.isPresent()) {
43-
return cellByCoordinates.get();
44-
} else throw new IllegalArgumentException("No cell with "
45-
+ "\n y: " + y
46-
+ "\nx: " + x);
40+
public Optional<Cell> getCell(int y, int x) {
41+
return cells.stream().filter(cell -> cell.x == x && cell.y == y).findFirst();
4742
}
4843

4944
public SliceInstruction getSliceInstruction() {
@@ -81,7 +76,11 @@ private String outputCellsArray() {
8176
//output rows coordinates
8277
stringBuilder.append(row).append(" ");
8378
for (int column = 0; column < columnsCount + 1; column++) {
84-
stringBuilder.append(this.getCell(row, column).toString()).append(" ");
79+
if (this.getCell(row, column).isPresent()) {
80+
stringBuilder.append(this.getCell(row, column).get().toString()).append(" ");
81+
} else {
82+
stringBuilder.append(" ").append(" ");
83+
}
8584
}
8685
stringBuilder.append("\n");
8786
}

src/main/java/com/google/hashcode/entity/Slice.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,20 @@
1313
*/
1414
public class Slice {
1515
private static final Logger LOGGER = LoggerFactory.getLogger(Slice.class);
16+
1617
public List<Cell> cells = new ArrayList<>();
1718

1819
public Slice() {
1920
}
2021

21-
public Slice(Cell cell) {
22-
this.cells = Collections.singletonList(cell);
22+
public Slice(Cell... cell) {
23+
this.cells = Arrays.asList(cell);
2324
}
2425

2526
public Slice(List<Cell> cells) {
2627
this.cells = cells;
2728
}
2829

29-
public List<Cell> getCells() {
30-
return cells;
31-
}
32-
3330
@Override
3431
public boolean equals(Object o) {
3532
if (this == o) return true;

src/main/java/com/google/hashcode/utils/DFSMethods.java

Lines changed: 30 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
66

7-
import java.util.*;
7+
import java.util.ArrayList;
8+
import java.util.HashMap;
9+
import java.util.List;
10+
import java.util.Map;
811
import java.util.stream.Collectors;
912

1013
public abstract class DFSMethods {
@@ -13,44 +16,6 @@ public abstract class DFSMethods {
1316
private DFSMethods() {
1417
}
1518

16-
/**
17-
* Step as an entity is an amount of a pizza cells, that can be added to a slice of a pizza or a pizza cell.<br>
18-
* Step as an action is a process of:<br>
19-
* <p>
20-
* * adding cells to a start cell or a start slice<br>
21-
* * validate generated slice according to the pizza slicing instructions<br>
22-
* * if validation passed ->cutting the start cell with added cells from the pizza
23-
*
24-
* @param pizza (mutable) a pizza to perform step on
25-
* @param slice start position for a step
26-
* @return cutted slice from the pizza
27-
*/
28-
public static Optional<Slice> rightStep(Pizza pizza, Slice slice) {
29-
List<Cell> slicesRightBorder = slice.cells.stream()
30-
.filter(cell -> (cell.x == slice.maxX()) && (cell.y >= slice.minY()) && (cell.y <= slice.maxY()))
31-
.collect(Collectors.toList());
32-
//each cell should have a cell right side of it in the pizza
33-
try {
34-
Slice step = new Slice(slicesRightBorder.stream()
35-
.map(slicesRightBorderCell -> pizza.getCell(slicesRightBorderCell.y, slicesRightBorderCell.x + 1))
36-
.collect(Collectors.toList()));
37-
//check is step is valid
38-
Slice sliceAndStep = new Slice(new ArrayList(slice.cells));
39-
sliceAndStep.cells.addAll(step.cells);
40-
if (!slice.cells.isEmpty() && sliceAndStep.isValid(pizza)) {
41-
//remove the slice and step from the pizza
42-
pizza.getCells().removeAll(sliceAndStep.cells);
43-
return Optional.of(sliceAndStep);
44-
} else {
45-
return Optional.empty();
46-
}
47-
} catch (IllegalArgumentException e) {
48-
//if can't add at least one neccessary cell - > return an empty step
49-
LOGGER.info("Can't perform a step right !");
50-
return Optional.empty();
51-
}
52-
}
53-
5419
/**
5520
* For each slice find all available steps. We DON'T change the pizza on this stage
5621
*
@@ -87,14 +52,24 @@ public static Map<Slice, List<Step>> getAvailableSteps(Pizza pizza, List<Slice>
8752
* @param steps available steps
8853
* @return formed slice that includes an original slice and delta from a step
8954
*/
90-
public static List<Step> performStep(Pizza pizza, Map<Slice, List<Step>> steps) {
55+
public static Slice performStep(Pizza pizza, Map<Slice, List<Step>> steps) {
9156
//1. Pick ups a steps list with minimal total cells number
92-
final Optional<List<Step>> minStep = steps.values().stream().min((o1, o2) -> new StepsComparator().compare(o1, o2));
93-
return minStep.get();
57+
Step step = steps.values().stream().min((o1, o2) -> new StepsComparator().compare(o1, o2)).get().get(0);
58+
LOGGER.info("step to perform: " + step);
59+
//2. Cut all the step delta cells from pizza
60+
LOGGER.info("pizza before step: " + pizza
61+
+ "\ndelta to remove from the pizza: " + step.delta);
62+
pizza.getCells().removeAll(step.delta.cells);
63+
LOGGER.info("pizza after step:" + pizza);
64+
//3. Add the step cells to an output slice
65+
Slice slice = new Slice(step.delta.cells);
66+
slice.cells.addAll(step.startPosition.cells);
67+
return slice;
9468
}
9569

9670
/**
9771
* Finds a cells type with minimal cells numbers and generates one cell slices from them
72+
* Delete the slices from the pizza
9873
*
9974
* @param pizza given pizza
10075
* @return slices that are start positions for future slicing
@@ -109,15 +84,26 @@ public static List<Slice> cutAllStartPositions(Pizza pizza) {
10984
LOGGER.info("cutAllStartPositions for pizza: " + pizza
11085
+ "\nmushrooms number: " + mushrooms.size()
11186
+ "\ntomatoes number: " + tomatoes.size());
87+
List<Slice> startPositions = null;
11288
if (mushrooms.size() > tomatoes.size()) {
113-
return tomatoes.stream()
89+
startPositions = tomatoes.stream()
11490
.map(Slice::new)
11591
.collect(Collectors.toList());
92+
List<Cell> cellsToRemove = startPositions.stream()
93+
.flatMap(slice -> slice.cells.stream())
94+
.collect(Collectors.toList());
95+
pizza.getCells().removeAll(cellsToRemove);
11696
} else {
117-
return mushrooms.stream()
97+
startPositions = mushrooms.stream()
11898
.map(Slice::new)
11999
.collect(Collectors.toList());
100+
List<Cell> cellsToRemove = startPositions.stream()
101+
.flatMap(slice -> slice.cells.stream())
102+
.collect(Collectors.toList());
103+
pizza.getCells().removeAll(cellsToRemove);
120104
}
105+
LOGGER.info("pizza without start positions:" + pizza);
106+
return startPositions;
121107
}
122108

123109
}

src/test/java/com/google/hashcode/entity/PizzaTest.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66

77
import java.io.File;
88
import java.io.IOException;
9+
import java.util.Optional;
910

1011
import static com.google.hashcode.utils.InputFiles.EXAMPLE_INPUT_FILE_PATH;
1112
import static org.junit.Assert.assertEquals;
13+
import static org.junit.Assert.assertFalse;
1214

1315
/**
1416
* @author Grigoriy Lyashenko (Grog).
@@ -24,12 +26,13 @@ public void setup() throws IOException {
2426

2527
@Test
2628
public void getCell() throws Exception {
27-
assertEquals(examplePizza.getCell(0, 0), new Cell(0, 0, Ingredient.TOMATO));
29+
assertEquals(examplePizza.getCell(0, 0), Optional.of(new Cell(0, 0, Ingredient.TOMATO)));
2830
}
2931

30-
@Test(expected = IllegalArgumentException.class)
32+
@Test
3133
public void getCellException() throws Exception {
32-
examplePizza.getCell(100500, 0);
34+
Optional<Cell> cell = examplePizza.getCell(100500, 0);
35+
assertFalse(cell.isPresent());
3336
}
3437

3538
@Test

src/test/java/com/google/hashcode/utils/DFSMethodsTest.java

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
import java.io.File;
88
import java.io.IOException;
9-
import java.util.ArrayList;
109
import java.util.Arrays;
1110
import java.util.List;
1211
import java.util.Map;
@@ -26,18 +25,6 @@ public void setup() throws IOException {
2625
pizza = new Pizza(new File(EXAMPLE_INPUT_FILE_PATH), IoUtils.parsePizza(EXAMPLE_INPUT_FILE_PATH), IoUtils.parseSliceInstructions(EXAMPLE_INPUT_FILE_PATH));
2726
}
2827

29-
@Test
30-
public void rightStep() throws Exception {
31-
//then perform a step right from a particular cell
32-
Slice actualSlice = DFSMethods.rightStep(pizza, new Slice(pizza.getCell(1, 3))).get();
33-
Slice expectedSlice = new Slice(Arrays.asList(new Cell(1, 3, Ingredient.MUSHROOM), new Cell(1, 4, Ingredient.TOMATO)));
34-
assertEquals(expectedSlice, actualSlice);
35-
//and slice has been removed from the pizza
36-
ArrayList<Cell> expectedPizzaCells = new ArrayList<>(pizza.getCells());
37-
expectedPizzaCells.removeAll(expectedSlice.cells);
38-
assertEquals(expectedPizzaCells, pizza.getCells());
39-
}
40-
4128
@Test
4229
public void getAvailableSteps() throws IOException {
4330
Map<Slice, List<Step>> actualMap = DFSMethods.getAvailableSteps(pizza, DFSMethods.cutAllStartPositions(pizza));
@@ -55,12 +42,14 @@ public void cutAllStartPositions() throws IOException {
5542
new Slice(new Cell(1, 3, Ingredient.MUSHROOM))
5643
);
5744
assertEquals(expected, DFSMethods.cutAllStartPositions(pizza));
45+
assertEquals("We expect pizza size reduced to 15-3=12", 12, pizza.getCells().size());
5846
}
5947

6048
@Test
6149
public void performStep() {
62-
//TODO finish the method implementation
63-
List<Step> minSteps = DFSMethods.performStep(pizza, DFSMethods.getAvailableSteps(pizza, DFSMethods.cutAllStartPositions(pizza)));
64-
System.err.println(minSteps);
50+
List<Slice> output = DFSMethods.cutAllStartPositions(pizza);
51+
Slice slice = DFSMethods.performStep(pizza, DFSMethods.getAvailableSteps(pizza, output));
52+
assertEquals(new Slice(Arrays.asList(new Cell(0, 2, Ingredient.TOMATO), new Cell(1, 2, Ingredient.MUSHROOM))), slice);
53+
assertEquals(11, pizza.getCells().size());
6554
}
6655
}

0 commit comments

Comments
 (0)