Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Solution {
  5.  
  6. public static void main(String[] args) {
  7.  
  8. //initializing regular code...
  9. Scanner s = new Scanner(System.in);
  10. int n = s.nextInt();
  11. int d = s.nextInt();
  12. int[] arr = new int[n];
  13. for(int i = 0; i < n; i++)
  14. arr[i] = s.nextInt();
  15.  
  16. //for optimal solution, if n==d or d is multiple of n then we do nothing.
  17. //example: move array of 5 elements, 5 place to the left. We do nothing.
  18. //Therefor we remove from d the multiple of n.
  19.  
  20. //if d is not multiple of n
  21. if(d%n != 0) {
  22. if(d > n) {
  23. while(d>n) {
  24. //here we remove n from d. (But we need to check when to stop.)
  25. if(d < n)
  26. break;
  27. d -= n;
  28. }
  29. }
  30. /*
  31. after all the work we got d that is 100% less than n. which is good, so we don't need to do mutliple
  32. rotations to get to the same result.
  33.  
  34. My optimal solution:
  35.  
  36. Create new list of size n. Add all elements from arr[] to new list, starting from index d (included)
  37. up to index arr.length (which is n) . That way only the "rotating elements from left to right" will
  38. be added later, and the "not rotating elements from left to right" are added immidietly, without checking.
  39. */
  40.  
  41. int[] newArr = new int[n];
  42. for(int i = 0; i < (n - d); i++)
  43. newArr[i] = arr[d+i];
  44.  
  45. //we done adding all "non rotating elements"
  46. //now append all "moving elements"
  47. //they are in arr[] from index (include) 0 to index (include) d-1 .
  48.  
  49. for(int i = 0; i < d; i++)
  50. newArr[n-d+i] = arr[i];
  51.  
  52. //and we done!
  53. //print result
  54. for(int i = 0; i < n; i++)
  55. System.out.print(newArr[i] + " ");
  56. }
  57. else
  58. //print result
  59. for(int i = 0; i < n; i++)
  60. System.out.print(arr[i] + " ");
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement