Skip to content

Instantly share code, notes, and snippets.

@gabtoschi
Created November 28, 2020 00:50
Show Gist options
  • Save gabtoschi/5f1b74688a65ad205924c2bdbc36aa7d to your computer and use it in GitHub Desktop.
Save gabtoschi/5f1b74688a65ad205924c2bdbc36aa7d to your computer and use it in GitHub Desktop.
Using modular arithmetic to move a robot in 4 directions
#include <stdlib.h>
#include <stdio.h>
#define TOTAL_POS 4
#define addMod(x, n) (x + 1) % n
#define subMod(x, n) (x - 1 + n) % n
int main(int argc, char const *argv[]){
int actualPosition = 0;
char positions[4][6] = {"North", "East", "South", "West"};
char pos;
do {
pos = getchar();
if (pos == 'l') actualPosition = subMod(actualPosition, TOTAL_POS);
if (pos == 'r') actualPosition = addMod(actualPosition, TOTAL_POS);
} while (pos != '\n');
printf("%s\n", positions[actualPosition]);
return 0;
}
// input example: llrlrlrlrlr\n
/*
Z(4) = {0, 1, 2, 3}
Left = -1
Right = +1
>>>> RIGHT
0 + 1 = 1 % 4 = 1
1 + 1 = 2 % 4 = 2
2 + 1 = 3 % 4 = 3
3 + 1 = 4 % 4 = 0
(actualPosition + 1) % TotalPos
>>>> LEFT
3 - 1 = (3 - 1 + 4) % 4 = 6 % 4 = 2
2 - 1 = (2 - 1 + 4) % 4 = 5 % 4 = 1
1 - 1 = (1 - 1 + 4) % 4 = 4 % 4 = 0
0 - 1 = (0 - 1 + 4) % 4 = 3 % 4 = 3
(actualPosition - 1 + TotalPos) % TotalPos
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment