K
K
KUKI_CHAR2019-01-13 14:54:43
C++ / C#
KUKI_CHAR, 2019-01-13 14:54:43

How to flip a random array in SI?

used two cycles, you need to make sure that there is only one.

#include<stdio.h>
int main() {
int a[10];
for(int i=0;i<10;i++){
a[i]=rand()%11;
printf("%d ", a[i]);}
int b[10];
int k=0;
for(int i=9;i>=0;i--){
b[k]=a[i];
k++;}
printf("\n\n");
for(int i=0;i<10;i++){
printf("%d ",b[i]);}
return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-01-13
@myjcom

From what the question is and what is written it is not clear what you want.
if you have 2 arrays just copy one to the other in reverse order.
if you have one array, then you can write the reverse(first, last) function and swap the elements.
in both cases one cycle.

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

void swap(int* a, int* b)
{
    int c = *a;
    *a = *b;
    *b = c;
}

void reverse(int* first, int* last)
{
    while((first != last) && (first != --last))
    {
        swap(first++, last);
    }
}

int* reverse_copy(int* first, int size)
{
    int* result = (int*)malloc(size * sizeof(int));
    for(int i = 0; i < size; ++i)
    {
        result[i] = first[size - i - 1];
    }
    return result;
}

int main()
{
    int a[] = {0,1,2,3,4,5,6,7,8,9};
    reverse(a, &a[10]);
    for(int i = 0; i < 10; ++i)
    {
        printf("%d ", a[i]);
    }

    printf("\n");

    int* b = reverse_copy(a, 10);

    for(int i = 0; i < 10; ++i)
    {
        printf("%d ", b[i]);
    }
    free(b);
}

OUT:
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question