Skip to content

Commit 898b7f2

Browse files
committed
feat: add Partitions utility class
1 parent d2ec09a commit 898b7f2

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.adventofcode.flashk.common;
2+
3+
import module java.base;
4+
5+
/// Utility class to make partitions of Strings, Lists etc.
6+
public class Partitions {
7+
8+
private Partitions() {}
9+
10+
/// Creates a List of Strings with the given partition size
11+
///
12+
/// Example:
13+
///
14+
/// ```
15+
/// Partitions.fromString("abcd", 1); // ["a","b","c","d"]
16+
/// Partitions.fromString("abcd", 2); // ["ab","cd"]
17+
/// Partitions.fromString("abcd", 3); // ["abc","d"]
18+
/// ```
19+
/// @param text the text to create the partition from
20+
/// @param partitionSize the size of the partition
21+
/// @return a list containing all the partitions created from the text.
22+
public static List<String> fromString(String text, int partitionSize) {
23+
List<String> results = new ArrayList<>();
24+
25+
int length = text.length();
26+
27+
for (int i = 0; i < length; i += partitionSize) {
28+
results.add(text.substring(i, Math.min(length, i + partitionSize)));
29+
}
30+
31+
return results;
32+
}
33+
34+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.adventofcode.flashk.common;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
import static java.lang.IO.println;
5+
6+
import module java.base;
7+
import org.junit.jupiter.api.Test;
8+
9+
class PartitionsTest {
10+
11+
@Test
12+
void fromStringPartitionSize1() {
13+
14+
List<String> result = Partitions.fromString("abcd", 1);
15+
16+
assertEquals(4, result.size());
17+
assertEquals("a", result.get(0));
18+
assertEquals("b", result.get(1));
19+
assertEquals("c", result.get(2));
20+
assertEquals("d", result.get(3));
21+
}
22+
23+
@Test
24+
void fromStringPartitionSize2() {
25+
26+
List<String> result = Partitions.fromString("abcd", 2);
27+
28+
assertEquals(2, result.size());
29+
assertEquals("ab", result.get(0));
30+
assertEquals("cd", result.get(1));
31+
32+
}
33+
34+
@Test
35+
void fromStringPartitionSize3() {
36+
List<String> result = Partitions.fromString("abcd", 3);
37+
38+
assertEquals(2, result.size());
39+
assertEquals("abc", result.get(0));
40+
assertEquals("d", result.get(1));
41+
}
42+
43+
@Test
44+
void fromStringPartitionSize4() {
45+
List<String> result = Partitions.fromString("abcd", 4);
46+
47+
assertEquals(1, result.size());
48+
assertEquals("abcd", result.getFirst(0));
49+
}
50+
51+
}

0 commit comments

Comments
 (0)