desislava_topuzakova

04. Array Rotation

Jun 5th, 2021
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3.  
  4. public class Demo_2 {
  5.     public static void main(String[] args) {
  6.         Scanner scanner = new Scanner(System.in);
  7.         //масив
  8.         String input = scanner.nextLine(); //"51 47 32 61 21"
  9.         String[] numbers = input.split(" ");//"51 47 32 61 21".split(" ") -> ["51", "47", "32", "61", "21"]
  10.         int countRotations = Integer.parseInt(scanner.nextLine()); //брой на ротациите
  11.  
  12.         for (int rotation = 1; rotation <= countRotations; rotation++) {
  13.             //ротация
  14.             //1. взимам си първия елемент
  15.             String firstElement = numbers[0];
  16.             //2. местя всички елементи с 1 наляво (индексът на елемента = индекс - 1
  17.             for (int index = 0; index < numbers.length - 1; index++) {
  18.                 numbers[index] = numbers[index + 1];
  19.             }
  20.             //3. на последния индекс = първия елемент
  21.             numbers[numbers.length - 1] = firstElement;
  22.         }
  23.  
  24.         System.out.println(String.join(" ", numbers));
  25.  
  26.  
  27.     }
  28. }
  29.  
Advertisement
Add Comment
Please, Sign In to add comment