Question

I'm solving gray code problem. I made my logic using recursive call. Everything look ok but I have no idea how to prefix '0' or '1' to each element of an array. eg) prefix 0 : { 00, 01, 11, 10 } -> { 000, 001, 011, 010 } or prefix 1 : { 00, 01, 11, 10 } -> { 100, 101, 111, 110 }

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

int grayCode(int list[], int bit)
{
    int listLen = strlen(list); // calculate received array length
    int revList[] = { 0 };
    int newList[] = { 0 };

    if (listLen < pow(2, bit)) // If the received array length is below 2^bit, proceed below.

    {
        for (int i = 0; i < listLen; i++) // create a reverse order array
        {
            revList[i] = list[listLen - i];
        }

        for (int i = 0; i < listLen; i++) // prefix 0 to each element of an received array, I know this doesn't work. How should I do it??
        {
            list[i] = "0" + list[i];
        }

        for (int i = 0; i < listLen; i++) // prefix 1 to each element of an reverse array, I know this doesn't work. How should I do it??
        {
            revList[i] = "1" + revList[i];
        }

        for (int i = 0; i < listLen; i++)  // put all elements of received array in the new array
        {
            newList[i] = list[i];
        }

        for (int i = 0; i < listLen; i++)  // put all elements of reverse array in the new array
        {
            newList[listLen + i] = revList[i];
        }

        for (int i = 0; i < listLen * 2; i++)  // print all elements in a new array
        {
            printf("%d bit Gray Code is { ", bit);
            printf("%d, ", newList[i]); 
            printf("}\n");
        }

        grayCode(newList, bit); // Recursive call
    }

    else if (listLen == pow(2, bit)) // If the received array length is same as 2^bit, return.
    {
        return 0;
    }
}

int main(void)
{
    int initList[2] = { 0, 1 };
    int bit;

    printf("Which bit of gray-code do you want? : ");
    scanf_s("%d", &bit);

    while (bit < 1)
    {
        printf("Input an integer bigger than 1 : ");
        scanf_s("%d", &bit);
    }

    if (bit == 1)
    {
        printf("1 bit Gray Code is { 0, 1 }\n");
    }

    else if (bit > 1)
    {
        grayCode(initList, bit);
    }

    return 0;
}
Was it helpful?

Solution

No, you can't append 0 as prefix to an integer.
An integer starting with 0 is assumed as octal representation of corresponding decimal integer, i.e.:

(037)8 == (31)10

If you really want to save the numbers with prefixed 0s, you will have to store the numbers as strings.

You can use a temporary string for storing intermediates.

The algorithm will be:

char str[10] = "01";      // To be converted to 001
char temp[10];

strcpy(temp, "0");     // temp = "0", str = "01"
strcat(temp, str);     // temp = "001", str = "01"
strcpy(str, temp);     // temp = "001", str = "001"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top