From 993716627a616e821aefd8707230221d0dac6cd7 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Thu, 27 Dec 2018 09:48:28 -0600 Subject: Knapsack partition3 done! I used the "sleep on it" technique and the algo came to me about the time I fall asleep. I started working on this based on algo I thought in my head first thing after my run and shower, and it worked! I then went to edX forum to see what other people are saying. Frankly those forum posts were confusing to me.--- .../sources/Partition3.java | 63 ++++++++++++++++++++++ .../tests/Partition3Test.java | 25 +++++++++ 2 files changed, 88 insertions(+) create mode 100644 AlgoDesignAndTechniqueEdxJava/sources/Partition3.java create mode 100644 AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java diff --git a/AlgoDesignAndTechniqueEdxJava/sources/Partition3.java b/AlgoDesignAndTechniqueEdxJava/sources/Partition3.java new file mode 100644 index 0000000..546fcb2 --- /dev/null +++ b/AlgoDesignAndTechniqueEdxJava/sources/Partition3.java @@ -0,0 +1,63 @@ +import java.util.Scanner; + +public class Partition3 { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int n = scanner.nextInt(); + int[] A = new int[n]; + for (int i = 0; i < n; i++) { + A[i] = scanner.nextInt(); + } + System.out.println(partition3(A)); + } + + public static int partition3(int[] a) { + if (a.length < 3) + return 0; + int sum = 0; + for (int i = 0; i < a.length; i++) { + sum = sum + a[i]; + } + if (sum % 3 != 0) + return 0; + int W = sum / 3; + int[][] values = optimalWeight2DArray(W, a); + int count = 0; + for (int i = 1; i < a.length + 1; i++) { + for (int w = 1; w < W + 1; w++) { + if (values[w][i] == W) + count = count + 1; + } + } + if (count >= 3) + return 1; + else + return 0; + } + + public static int[][] optimalWeight2DArray(int W, int[] w2) { + int j = w2.length; + int[][] value = new int[W + 1][j + 1]; + + for (int i = 0; i < j + 1; i++) { + for (int w = 0; w < W + 1; w++) { + if (i == 0 || w == 0) { + value[w][i] = 0; + continue; + } + value[w][i] = value[w][i - 1]; + if (w2[i - 1] <= w) { + int val = value[w - w2[i - 1]][i - 1] + w2[i - 1]; + if (value[w][i] < val) { + value[w][i] = val; + } + } + } + + } + + return value; + } + +} diff --git a/AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java b/AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java new file mode 100644 index 0000000..593d21a --- /dev/null +++ b/AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java @@ -0,0 +1,25 @@ +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class Partition3Test { + + @Test + void test() { + int[] a = {3, 3, 3, 3}; + assertEquals(0, Partition3.partition3(a)); + } + + @Test + void test1() { + int[] a = {30}; + assertEquals(0, Partition3.partition3(a)); + } + + @Test + void test2() { + int[] a = {1, 2, 3, 4, 5, 5, 7, 7, 8, 10, 12, 19, 25}; + assertEquals(1, Partition3.partition3(a)); + } + +} -- cgit v1.2.3