You are given a binary compass which shows the direction you are safe to go to.
The binary compass read n binary digits (bits) which interprets 1 to rotate 90°
to
the left and 0 rotate 90°
to the right. Initially you are facing North. Create a program
for this binary compass.
#include <stdio.h>
int binary_compass(int bits[], int n) {
int i, dir=0;
for (i=0; i<n; i++) {
if (bits[i]) {
dir++;
}
else {
dir--;
}
if (dir > 4) {
dir -= 4;
}
else if (dir < 0) {
dir += 4;
}
}
return dir;
}
char* direction(int dir) {
switch (dir) {
case 0:
return "nord";
case 1:
return "west";
case 2:
return "south";
case 3:
return "east";
}
return "Stop";
}
int main() {
int bits[100];
int i, n;
int dir;
printf("Enter n: ");
scanf("%d", &n);
printf("Enter %d bits: ", n);
for (i=0; i<n; i++) {
scanf("%d", &bits[i]);
}
dir = binary_compass(bits, n);
printf("Go %s\n", direction(dir));
return 0;
}
Comments
Leave a comment