user1546616 user1546616 - 1 month ago 8
C Question

Swap first number with second, second with third et cetera

I have been given a random checksum algorithm that works this way


  1. enter the number (up to 1 000 000)

  2. the algorithm is n[0]-n[1]+n[2]-n[3] so it's just adding and subtracting parts of the number. If the number is 1243 then 1-2+4-3=0.



If the result is 0 then the checksum passed. If not, I need to swap numbers: First with second, then try, if won't work, second with third, then try and so on. So for 224 it would give me 0 by replacing second 2 and 4.

So far my code is:

#include <stdio.h>
#include <stdlib.h>

int intlen (long long n)
{
int len = 1;
while ( abs (n) > 9 )
{
n /= 10;
++len;
}
return len;
}
short getDigit (long long num, int index)
{
int pos = intlen (num) - index;
while ( pos > 1 )
{
num /= 10;
--pos;
}
if(intlen(num) <= index) {
return 0;
}
return num % 10;
}
int checkSum(int pin) {
int wynik = 0;
int typ = 0;
int i = 0;
for(i = 0; i < intlen(pin); i=i+3) {
if(typ == 0) {
wynik += getDigit(pin, i) - getDigit(pin, i+1) + getDigit(pin, i+2);
typ = 1;
} else {
wynik -= getDigit(pin, i) - getDigit(pin, i+1) + getDigit(pin, i+2);
typ = 0;
}
}
return wynik;
}
int main()
{
int wynik, pin;
scanf("%d", &pin);
wynik = checkSum(pin);
printf("CS: %d\n", wynik);
system("pause");
return 0;
}


But I don't really know on how to do the swapping part. Could someone enlighten me the way on how to do it?

Answer

Maybe I don't understand what you want to do, but if I did understand correctly this is all you need:

#include <stdio.h>
#include <string.h>

int checkSum(char pin[])
{
    int wynik = 0;
    int sub = 0;
    int i = 0;

    for (i = 0; i < strlen(pin); i++, sub=!sub)
    {
        // use pin[I] - '0' to get the number stored in the array location
        // use sub?-1:1 * X to either subtract or add by multiplying by -1
        wynik = wynik + (sub?-1:1) * (pin[i]-'0');
    }

    return wynik;
}

int main()
{
    char pin[8]; // enough to hold 1000000\0
    int wynik;
    int swap;
    int i=0;  

    puts("Enter pin:");
    scanf("%s", &pin);

    // update checksum
    wynik = checkSum(pin);
    printf("PIN=%s CS=%d\n", pin,wynik);

    for (i = 0; wynik != 0 && i < strlen(pin) - 1; i++)
    {
        // swap pin[i] with pin[i+1]
        swap = pin[i]; pin[i] = pin[i+1]; pin[i+1] = swap;

        // update checksum
        wynik = checkSum(pin);
        printf("PIN=%s CS=%d\n", pin,wynik);
    }
}

The whole thing is easier if you use an array and a string is an array of characters so that's almost perfect - the only thing you need to do to get the digit at some array index is subtract '0' from the value at that index. The reason this works is that the characters '0' through '9' are contiguous. That means you don't need getDigit() and intlen() can be replaced by strlen()