Answer to Question #311480 in C for Daniel

Question #311480

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. 


1
Expert's answer
2022-03-15T12:12:25-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS