From 0b897ff02472d64d651c6a2e7d5f00311063a9fc Mon Sep 17 00:00:00 2001 From: teivaz Date: Wed, 13 Jan 2016 13:37:26 +0200 Subject: [PATCH 1/2] Better solution for 5_7 with xor sum and without recursion --- c++/Chapter 5/Question5_7.cpp | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/c++/Chapter 5/Question5_7.cpp b/c++/Chapter 5/Question5_7.cpp index 8b0665a1..524acd5a 100644 --- a/c++/Chapter 5/Question5_7.cpp +++ b/c++/Chapter 5/Question5_7.cpp @@ -6,6 +6,28 @@ int fetchBit(int bit, int no){ return (no&1); } +int findMissingWithXor(int A[], int N){ + int n = 1; + int xorTarget = 1; + int xorActual = 0; + + int maxBytes = sizeof(int); // optimize to number of significant bits in N + for(int i = 0; i < N; ++i){ + + // Find the XOR sum of elements 0...N + // Possibly can optimzie without loop + xorTarget ^= ++n; + + // Sweep throug each bit (preferably significant) + // and calculate XOR sum of that + for(int j = 0; j < maxBytes; ++j){ + xorActual ^= (fetchBit(A[i], j) << j); + } + } + // XOR target and actual sums to find missing + return xorActual ^ xorTarget; +} + int findMissingUtils(int A[], int n, int col){ if(n <2){ return 0; @@ -39,6 +61,7 @@ void findMissing(int A[], int n){ int main(){ int A[] = {2, 5, 6, 0, 1, 3, 4, 8, 9, 10, 11, 12}; - findMissing(A, 12); + //findMissing(A, 12); + findMissingWithXor(A, 12); return 0; } \ No newline at end of file From 057db051b9db307afb4a10d3e2af373ab2e4e365 Mon Sep 17 00:00:00 2001 From: teivaz Date: Wed, 13 Jan 2016 16:02:33 +0200 Subject: [PATCH 2/2] Solution for 5_8 --- c++/Chapter 5/Question5_8.cpp | 46 ++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/c++/Chapter 5/Question5_8.cpp b/c++/Chapter 5/Question5_8.cpp index 35b2d3e8..33967f28 100644 --- a/c++/Chapter 5/Question5_8.cpp +++ b/c++/Chapter 5/Question5_8.cpp @@ -1,9 +1,53 @@ #include using namespace std; +void PrintScreen(unsigned char buffer[], int width, int height){ + int byteWidth = width / 8; + for(int row = 0; row < height; ++row){ + for(int column = 0; column < byteWidth; ++column){ + int index = row * byteWidth + column; + char block = buffer[index]; + for(int i = 7; i >= 0; --i){ + if( (block >> i) & 1){ + cout << '.'; + } + else{ + cout << ' '; + } + } + } + cout << '\n'; + } +} +void SetBit(unsigned char& byte, int bit){ + byte |= 1 << bit; +} -int main(){ +void DrawHorizontalLine(unsigned char buffer[], int bufferLength, int width, int x1, int x2, int y){ + int x = width * y + x1; + int end = width * y + x2; + while(x < end){ + int byteIndex = x / 8; + int bit = x - byteIndex * 8; + SetBit(buffer[byteIndex], 7 - bit); + ++x; + } +} +int main(){ + unsigned char screen[] = { + 0x80, 0x01, + 0x40, 0x02, + 0x20, 0x04, + 0x10, 0x08, + 0x08, 0x10, + 0x04, 0x20, + 0x02, 0x40, + 0x01, 0x80 + }; + PrintScreen(screen, 16, 8); + DrawHorizontalLine(screen, 2 * 8, 16, 5, 9, 2); + PrintScreen(screen, 16, 8); return 0; } \ No newline at end of file