0

First I generate some random numbers and then i need to exchange them like I discribte in the following lines. I tryed it iut with the for loobs.

I have to exchange the numbers of the array

  1. Change number 1 and 2, 3 and 4,.....29 and 30
  2. Change number 1 and 3, 4 and 7,.....27 and 30 Thank you for your Help

srand(time(NULL));
for ( i = 0; i < SIZE; i++ )
{
    mainArray[i] = rand() % ( UPPERBOUND - LOWERBOUND + 1 ) + LOWERBOUND;
}


for ( i = 0; i < SIZE; i++)
{

    if ( countDigitChange == 2 )
    {
        digitChanger1 = workArray2[i];
        i++;
        digitChanger2 = workArray2[i];
        workArray2[i] = digitChanger1;
        i--;
        workArray2[i] = digitChanger2;
        countDigitChange = 0;
    }
    countDigitChange++;
}
   for ( i = 0; i < SIZE; i++)
{
    if ( countDigitChange % 3 == 0 )
    {
        digitChanger1 = workArray3[i];
        i += 2;
        digitChanger2 = workArray3[i];
        workArray3[i] = digitChanger1;
        i += 2;
        workArray3[i] = digitChanger2;
        countDigitChange = 0;
    }
    countDigitChange++;
}
8
  • How does this code relate to what you want to do? Commented Feb 24, 2021 at 19:54
  • Are the numbers you mentioned already existing in the array? You say you need to "change" these numbers? What do you need to change them to? Commented Feb 24, 2021 at 20:03
  • There are random numbers and I need to exchange them Commented Feb 24, 2021 at 20:07
  • 2
    please post a minimal reproducible example Commented Feb 24, 2021 at 20:09
  • You say you need to exchange these numbers? With what do you need to exchange them? Commented Feb 24, 2021 at 21:26

1 Answer 1

1

This seems much simpler:

Declare a helper function:

void swap_int(int* x, int *y)
{
    int tmp = *x;
    *x = *y;
    *y = tmp;
}

Then in your code that needs to shuffle the array:

int i, j; // declare this up top with all your other variable declarations

// for each pair of elements swap them
for (i=0, j=1; j < SIZE; i+=2, j+=2)
{
   swap_int(&mainArray[i], &mainArray[j]);
}

// swap array[0] with array[2], then swap array[3] with array[5], etc...
for (i=0, j=2; j < SIZE; i+=3, j+=3)
{
   swap_int(&mainArray[i], &mainArray[j]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.