Skip to content

Commit 8ea7472

Browse files
committed
42-problems first problem
1 parent 95c8119 commit 8ea7472

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.shekhargulati.fortytwo_problems;
2+
3+
import java.util.AbstractMap.SimpleEntry;
4+
import java.util.ArrayList;
5+
import java.util.Arrays;
6+
import java.util.List;
7+
8+
/**
9+
* Taken an input a sequence of 2n real numbers.
10+
* Design an O(nlogn) algorithm that partitions the numbers into n pairs,
11+
* with the property that the partition minimizes the sum of maximum sum of a pair.
12+
*/
13+
public class Problem01 {
14+
15+
public static List<SimpleEntry<Integer, Integer>> pairs(int[] numbers) {
16+
/*
17+
Algorithm:
18+
1. Sort the numbers
19+
2. Iterate over half the list and put first number and last in a pair
20+
21+
Other algorithm feasible
22+
1. Sort numbers
23+
2. Create reverse numbers
24+
3. Take first half of zip of numbers and reverse
25+
let l = sort [1,9,5,3]
26+
let r = reverse l
27+
take (length l `div` 2) (zip l r)
28+
*/
29+
Arrays.sort(numbers);
30+
List<SimpleEntry<Integer, Integer>> pairs = new ArrayList<>();
31+
for (int i = 0; i < numbers.length / 2; i++) {
32+
pairs.add(new SimpleEntry<>(numbers[i], numbers[(numbers.length - i) - 1]));
33+
}
34+
return pairs;
35+
}
36+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.shekhargulati.fortytwo_problems;
2+
3+
import org.junit.Test;
4+
5+
import java.util.AbstractMap.SimpleEntry;
6+
import java.util.List;
7+
8+
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
9+
import static org.junit.Assert.assertThat;
10+
11+
public class Problem01Test {
12+
13+
@Test
14+
public void shouldCreatePairsByMinOfMaximumSumOfPairs() throws Exception {
15+
List<SimpleEntry<Integer, Integer>> pairs = Problem01.pairs(new int[]{1, 9, 3, 5});
16+
assertThat(pairs, contains(new SimpleEntry<>(1, 9), new SimpleEntry<>(3, 5)));
17+
}
18+
}

0 commit comments

Comments
 (0)