diff --git a/samsung/t2/main.c b/samsung/t2/main.c new file mode 100644 index 0000000..d8b89f7 --- /dev/null +++ b/samsung/t2/main.c @@ -0,0 +1,116 @@ +#include +#include +#include + +// #define BIG_SIZE (64) // that is 18 446 744 073 709 551 616 paths to check +#define BIG_SIZE (32) // that is 4 294 967 295 paths to check, takes about 30 seconds on i7 3.60GHz + +// NOTE: This is probably not the best way to do this. +// A tricky case example is: +// X = 1, Y = 100, +// A = {1, 10, 1, 1, 1}, +// B = {10, 1, 1, 1, 1000} + +// NOTE: The idea is to start from the end (N-1) and assume that we +// have already found the best paths for previous nodes and pick the +// lower sum for current nodes. While checking previous nodes the +// function is called recursively so it again assumes that previous +// nodes are already solved. Since the first pair of nodes are just +// integers to be compared, we stop the recursion and the "unwinded" +// stack gives us the answer. + +int solution_(int A[], int B[], int N, int X, int Y, char onA) +{ + if (N == 0) { + return onA ? A[0] : B[0]; + } + + int c1, c2; + if (onA) { + c1 = 0 + A[N] + solution_(A, B, N-1, X, Y, 1); + c2 = Y + A[N] + solution_(A, B, N-1, X, Y, 0); + } + else { + c1 = 0 + B[N] + solution_(A, B, N-1, X, Y, 0); + c2 = X + B[N] + solution_(A, B, N-1, X, Y, 1); + } + + return (c1 <= c2 ? c1 : c2); +} + +int solution(int A[], int B[], int N, int X, int Y) +{ + int sa = solution_(A, B, N-1, X, Y, 1); + int sb = solution_(A, B, N-1, X, Y, 0); + return (sa <= sb ? sa : sb); +} + +void test(int actual, int expected) +{ + if (actual != expected) { + printf("Test failed, expected %i, got %i\n", expected, actual); + } + else { + printf("Test passed (expected %i, got %i)\n", expected, actual); + } +} + +int main() +{ + { + int A[] = {1, 6}; + int B[] = {3, 2}; + int N = 2, X = 2, Y = 10; + test(solution(A, B, N, X, Y), 5); + } + + { + int A[] = {1, 6, 2}; + int B[] = {3, 2, 5}; + int N = 3, X = 2, Y = 1; + test(solution(A, B, N, X, Y), 8); + } + + { + int A[] = {2, 11, 4, 4}; + int B[] = {9, 2, 5, 11}; + int N = 4, X = 8, Y = 4; + test(solution(A, B, N, X, Y), 21); + } + + { + int A[] = {1, 10, 1}; + int B[] = {10, 1, 10}; + int N = 3, X = 1, Y = 5; + test(solution(A, B, N, X, Y), 9); + } + + { + int A[] = {8, 3, 3}; + int B[] = {6, 1, 10}; + int N = 3, X = 4, Y = 3; + test(solution(A, B, N, X, Y), 13); + } + + { + int A[] = {1, 10, 1, 1}; + int B[] = {10, 1, 1, 100}; + int N = 4, X = 1, Y = 100; + test(solution(A, B, N, X, Y), 13); + } + + { + int A[BIG_SIZE]; + int B[BIG_SIZE]; + int N = BIG_SIZE, X = 1, Y = 100; + memset(A, 0, sizeof(A)); + memset(B, 0, sizeof(A)); + A[0] = 1; + B[0] = 10; + B[BIG_SIZE-1] = 100; + test(solution(A, B, N, X, Y), 1); + } + + + printf("Done\n"); +} \ No newline at end of file diff --git a/samsung/t2/samsung_t2.jpg b/samsung/t2/samsung_t2.jpg new file mode 100644 index 0000000..75f8168 Binary files /dev/null and b/samsung/t2/samsung_t2.jpg differ