1

I have 2d array (10x12), and they have 0 and 1s in them. I want to count the 1s in each array and I have two cases here: (1) if an array has more than three 1s, say k many, then generate k - 3 random variables and replace that many 1s with 0s if that random variable corresponds to a 1. (2)if an array has less than three 1s, say q many, then generate 3 - q random variables and replace that many 0s with 1s if that random variable corresponds to a 0. I have the following code so far. I need some suggestions here, I could not construct the code well.

int y[10];
int r[10];

for(int i=0; i < 10; i++)
{          
    for(int j=0; j < 12; j++)
    {
        y[i] += Array[i][j]; 
    }

    if(y[i] > 3)
    {
        f = y[i] - 3;
        if(Array[i][r[f]] ==1)
            Array[i][r[f]] = 0;
    }

    if(y[i] < 3)
    {
        f = 3 - y[i];
        if(Array[i][r[f]] ==0)
            Array[i][r[f]] = 1;
    }
}

Thanks

1 Answer 1

0

This should get you started:

#define ROW                (10)
#define COL                (12)
#define NUM_ONES_THRESHOLD (3)

int numOnes = 0, elementsToModify, randRow, randCol;
bool toggleUp;

/* Count 1s */
for(int row = 0; row < ROW; row++)
{
    for(int col = 0; col < COL; col++)
        numOnes += Array[row][col];   
}

/* Determine How Many Elements To Modify */
if(numOnes > NUM_ONES_THRESHOLD)
{
    elementsToModify = numOnes - NUM_ONES_THRESHOLD;
    toggleUp = false;
}
else
{
    elementsToModify = NUM_ONES_THRESHOLD - numOnes;
    toggleUp = true;
}

/* Modify Table */
while(elementsToModify > 0)
{
    randRow = rand() % ROW;
    randCol = rand() % COL;

    if((Array[randRow][randCol] == 1) && !toggleUp)
    {
        Array[randRow][randCol] = 0;
        elementsToModify --;
    }

    if((Array[randRow][randCol] == 0) && toggleUp)
    {
        Array[randRow][randCol] = 1;
        elementsToModify --;
    }
}

It can be optimized. I'll leave that as an exercise for you...

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.