Home > database >  Circular permutation in C
Circular permutation in C

Time:11-08

Given a array x with n integer components, write functions that allow performing the following operation: Carry out the circular permutation of the given array

I tried to do without poiters for the code, as it ends up with only arrays

I think the problem is that the array in the pcircular is lost and can't pass the value to the write function

Note: for array > 6 it will not work

#include <stdio.h>

int ArraySize(){   // get the size of the array
    int size;
    printf("What's the array size? ");
    scanf("%d", &size);
    return size;
}

void readArray(int size, int array[]){ /*put the values ​​in the first array*/
    for (int i = 0; i < size; i  ){
        printf("What is the \033[1;36m%d\033[m value? ", i 1);
        scanf("%d", &array[i]);
    }
}
void pcircular(int size, int array[size][size]){ //Circular permutation function
    for (int j = 0; j <= size; j  ){
        /* printf("("); */
        for (int i = 0; i < size; i  ){
            if (i == size - 1){
                array[j 1][0] = array[j][i];
                /* printf("%d", array[j 1][0]); */
            }
            else{
                array[j 1][i 1] = array[j][i];
                /* printf("%d", array[j 1][i 1]);
                printf(", "); */
            }
        }
        /* printf(")"); */
        
    }
    
} 
void writeArray(int size, int array[size][size]){ //Write the Array
    for (int i = 0; i <= size; i  ){
        printf("(");
        for (int j = 0; j < size; j  ){
            /* printf("\ni = %d j = %d\n", i, j);  */
            printf("%d", array[i][j]);
            if (j != size-1){
                printf(", ");
            }
        }
        printf(")");
    }
    
}

void main(){
    int size = ArraySize();
    int list[size][size];     // create the array
    readArray(size, list[0]);
    pcircular(size, list);
    writeArray(size, list);
}

Input:

What's the array size? 6

What is the 1 value? 1

What is the 2 value? 2

What is the 3 value? 3

What is the 4 value? 4

What is the 5 value? 5

What is the 6 value? 6

Expected Output: (1, 2, 3, 4, 5, 6)(6, 1, 2, 3, 4, 5)(5, 6, 1, 2, 3, 4)(4, 5, 6, 1, 2, 3)(3, 4, 5, 6, 1, 2)(2, 3, 4, 5, 6, 1)(1, 2, 3, 4, 5, 6)

Real Output: (

CodePudding user response:

write your pcircular function as follow:

void pcircular(int size, int array[size][size]){ //Circular permutation
    for (int j = 1; j <= size; j  ){
        for (int i = 0; i < size; i  ){
            array[j][i ] = array[j - 1][(i   1) % size];
        }        
    }
}

but the main problem is here:

int list[size   1][size];     // create the array

since you are creating one more row than the number, indeed the last row is copy of the first row.

if you dont change the pcircular function, and use your version, you should as well add to second dimention too.

  • Related