Way of learning java 8

Rotate Right array elements

An array A of there N ( > 0> 0 > 0 ) integer, the premise is not allowed use of additional arrays, each of the integer to the right cycle M ( ≧ 0 \ GE 0 0 ) position,

Coming A data by ( A0A1-⋯ the AN. 1 ) is converted into ( the AN-M-1A0A1 ⋯ ⋯ the AN-M-the AN. 1 ) (the last M the number of cycles to move the foremost M positions). If you need to consider the number of times a program to move data as little as possible, to how to design a way to move?

Input formats:

Each input comprises a test case, the first input line N ( 1 <= N <= 100) and M ( ≧ 0 ); a second input line N integers, separated by spaces in between.

Output formats:

Rotate Right output in a row M integer sequence after bit, separated by a space between, the end of the sequence can not have extra space.

Sample input:

6 2
1 2 3 4 5 6

Sample output:

5 6 1 2 3 4


That Italy appreciated: Suppose n=6required shift sequence is: 1 2 3 4 5 6if m=2, from 6 starts to see, to 6
moved two positions, 6 on to the position 2, similarly to 5 is moved two positions, 5 to the position 1, and so on.
Let us consider some special cases:
when m=0it is clear that the original sequence does not make any movement
when m=6, to move 6 6 position, the result is still the original sequence
when m=7, now m>n, according to the meaning of the questions this situation is possible, to put 6 7 position right movement, we found six moved to the 1 position.
Summing up the above analysis, we can draw, the number of mobilem = m % n

Problem-solving ideas:
no data movement, but to control the print order, such as number 6, [1 2 3 4 5 6 ], m = 2,
is moved two places to the right of all, we can first print 5 6, reprint1 2 3 4

#include <stdio.h>

int main () {
    int i;
    int n;
    int m;
    char ch = ''; // print control variables, default space
    int arr [100]; // index 0, the data does not exist

    scanf("%d", &n);
    scanf("%d", &m);
    m = m% n; // make sure that m <n

    // assign to the array
    for (i=1; i<=n; i++) {
        scanf("%d", &arr[i]);
    }

    // Next twice, each print order control
    // 1st printing, starting from the reciprocal number m
    for (i=n-m+1; i<=n; i++) {
        printf("%d ", arr[i]);
    }

    // // 2nd printing, from 1 to the number m of penultimate
    for (i=1; i<=n-m; i++) {
        if (i == (n - m)) {
            ch = '\ n';
        }
        printf("%d%c", arr[i], ch);
    }

    return 0;
}

Guess you like

Origin www.cnblogs.com/022414ls/p/11406958.html