Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better solution for 5_7 with xor sum and without recursion #135

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion c++/Chapter 5/Question5_7.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
46 changes: 45 additions & 1 deletion c++/Chapter 5/Question5_8.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,53 @@
#include<iostream>
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;
}