I'm Developing a Code for java to Fold the element inside an array with example
A[0] = 2, A[1] = 7, A[2] = 9, A[3] = 7
Then Fold it with this format
A[0] = (A[0] + A[3]) mod 10 = 9
A[1] = (A[1] + A[2]) mod 10 = 6
And Fold it again until single
A[0] = (A[0] + A[1]) mod 10 = 5
Below are incomplete code:
import java.util.ArrayList;
import java.util.List;
import java.lang.Math;
public class ArrayFolder {
public static void main(String[] args) {
//ArrayList
int[] A = {
2,
7,
9,
7
};
//To define a new Array later
List<Integer> intList = new ArrayList<Integer>();
//To print the ArrayList A
for (int x = 0; x < A.length; x++) {
System.out.println("A[" + x + "]= " + A[x]);
}
//Function to fold the ArrayList into half
int res = 0;
int result = 0;
//if A.length is Even
if (A.length % 2 == 0) {
for (int i = 0; i < A.length / 2; i++) {
res = A[i] + A[A.length - 1 - i];
result = res % 10;
intList.add(result);
}
}
//if A.length is Odd
else {
for (int i = 0; i < A.length / 2; i++) {
res = A[i] + A[A.length - 1 - i];
result = res % 10;
intList.add(result);
}
result = A[A.length / 2];
intList.add(result);
}
//add the int to New ArrayList
Integer[] intArray = new Integer[intList.size()];
intArray = intList.toArray(intArray);
System.out.println("\nNew Array ");
for (Integer s: intArray) {
System.out.println(s);
}
}
}
Compiled result
A[0]= 2
A[1]= 7
A[2]= 9
A[3]= 7
New Array
9
6
I couldn't find an efficient way to keep looping the function, so the code will stop folding when a single Integer achieved.
My question is, is there any efficient way to loop the process so later It can work with a larger element of Array?.
Kindly provide the logic or the code so I can continue with my code.
Many Thanks
You could put your folding algorithm into a separate method that returns you the folded array and call this method until you achieve a single Integer, for example like this:
import java.util.ArrayList;
import java.util.List;
public class ArrayFolder {
public static void main(String[] args) {
//ArrayList
Integer[] A = {
2,
7,
9,
7
};
while (A.length > 1) {
A = fold(A);
}
System.out.println("A[0]= " + A[0]);
}
private static Integer[] fold(Integer[] A) {
List<Integer> intList = new ArrayList<>();
//To print the ArrayList A
for (int x = 0; x < A.length; x++) {
System.out.println("A[" + x + "]= " + A[x]);
}
//Loop to fold the ArrayList into half
for (int i = 0; i < A.length / 2; i++) {
int res = A[i] + A[A.length - 1 - i];
int result = res % 10;
intList.add(result);
}
//if A.length is odd
if (A.length % 2 != 0) {
intList.add(A[A.length / 2]);
}
System.out.println("\n");
return intList.toArray(new Integer[intList.size()]);
}
}
You could also use a recursive method, i.e. the folding method will call itself for further folding until it reaches one Integer.
import java.util.ArrayList;
import java.util.List;
public class ArrayFolder {
public static void main(String[] args) {
//ArrayList
final Integer[] A = {
2,
7,
9,
7
};
fold(A);
}
private static void fold(Integer[] A) {
if (A.length > 0) {
List<Integer> intList = new ArrayList<>();
//To print the ArrayList A
for (int x = 0; x < A.length; x++) {
System.out.println("A[" + x + "]= " + A[x]);
}
//Loop to fold the ArrayList into half
for (int i = 0; i < A.length / 2; i++) {
int res = A[i] + A[A.length - 1 - i];
int result = res % 10;
intList.add(result);
}
//if A.length is odd
if (A.length > 1 && A.length % 2 != 0) {
intList.add(A[A.length / 2]);
}
System.out.println("\n");
fold(intList.toArray(new Integer[intList.size()]));
}
}
}
Folding in same array:
public static void main(String[] args) throws Exception {
int[] A = {2,7,9,7};
System.out.println("Input: " + Arrays.toString(A));
int length = A.length;
int mid = mid(length);
while(mid > 0) { //fold till only one left to fold
int i = 0;
for (; i <mid ; i++) { //single fold
int end = length-i-1;
if(i!=end) {
A[i] = (A[i] + A[end])%10;
}
}
System.out.println(Arrays.toString(Arrays.copyOf(A, mid)));
length = mid;
mid = mid(i);
}
System.out.println("Output: " + A[0]);
}
static int mid(int length) {
if(length == 1) return 0;
return (int)Math.ceil(length/2.0);
}
Output:
Input: [2, 7, 9, 7]
[9, 6]
[5]
Output: 5
For odd numbers:
Input: [2, 7, 3, 9, 7]
[9, 6, 3]
[2, 6]
[8]
Output: 8
Related
Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that an element of the array can be chosen only once to get sum S.
Example:
Input: arr[] = {25, 10, 5}, S = 30
Output: 2
Explanation:
Minimum possible solution is 2, (25+5)
Example:
Input: arr[] = {2, 1, 4, 3, 5, 6}, Sum= 6
Output: 1
Explanation:
Minimum possible solution is 1, (6)
I have found similar solution here but it says element of array can be used multiple times.
I have this code from the link which uses an array element multiple times, but how to restrict this to use only once?
static int Count(int S[], int m, int n)
{
int [][]table = new int[m + 1][n + 1];
// Loop to initialize the array
// as infinite in the row 0
for(int i = 1; i <= n; i++)
{
table[0][i] = Integer.MAX_VALUE - 1;
}
// Loop to find the solution
// by pre-computation for the
// sequence
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
if (S[i - 1] > j)
{
table[i][j] = table[i - 1][j];
}
else
{
// Minimum possible for the
// previous minimum value
// of the sequence
table[i][j] = Math.min(table[i - 1][j],
table[i][j - S[i - 1]] + 1);
}
}
}
return table[m][n];
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 9, 6, 5, 1 };
int m = arr.length;
System.out.print(Count(arr, m, 11));
}
The idiomatic approach for this is to loop backwards when updating the table of previous results.
static int minElementsForSum(int[] elems, int sum){
int[] minElems = new int[sum + 1];
for(int i = 1; i <= sum; i++) minElems[i] = Integer.MAX_VALUE;
for(int elem: elems)
for(int i = sum; i >= elem; i--)
if(minElems[i - elem] != Integer.MAX_VALUE)
minElems[i] = Math.min(minElems[i], minElems[i - elem] + 1);
return minElems[sum];
}
Demo
I've attempted to fix this but have failed so far. This is my first time dealing with sorting algorithms, for academic purposes, so I've likely made a simple mistake somewhere; I haven't been able to figure it out though.
private int[] mergeAndDivide(int[] array) {
if (array.length < 2)
return array;
int[] arrayOne = Arrays.copyOfRange(array, 0, (array.length - 1) / 2);
int[] arrayTwo = Arrays.copyOfRange(array, ((array.length - 1) / 2 + 1), (array.length - 1));
arrayOne = mergeAndDivide(arrayOne);
arrayTwo = mergeAndDivide(arrayTwo);
return merge(arrayOne, arrayTwo);
}
private int[] merge(int[] arrayOne, int[] arrayTwo) {
int[] arrayMerged = new int[arrayOne.length + arrayTwo.length];
int i = 0;
while (i <= arrayOne.length - 1 && i <= arrayTwo.length - 1) {
if (arrayOne[i] > arrayTwo[i])
arrayMerged[i] = arrayTwo[i];
else
arrayMerged[i] = arrayOne[i];
}
int x = i;
while (i <= arrayOne.length - 1) {
arrayMerged[i + arrayTwo.length - 1] = arrayOne[i];
i++;
}
i = x;
while (i <= arrayTwo.length - 1) {
arrayMerged[i + arrayOne.length - 1] = arrayTwo[i];
i++;
}
return arrayMerged;
}
Your code logic doesn't seems to be a merge sort.
This is the proper merge sort code :
public static void main(String[] args) {
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("\nSorted array");
for(int i=0;i<=arr.length-1;i++){
System.out.println("Initial Arr element:"+arr[i]);
}
mergeS(arr, 0, arr.length-1);
System.out.println("\nSorted array");
for(int i=0;i<=arr.length-1;i++){
System.out.println("Sorted Arr element:"+arr[i]);
}
}
public static void mergeS(int[] arr,int startI,int endI){
//System.out.println("StartIndex:"+startI+" EndIndex:"+endI)
if (startI< endI)
{
// Find the middle point
int m = (startI+endI)/2;
// Sort first and second halves
mergeS(arr,startI, m);
mergeS(arr , m+1, endI);
// Merge the sorted halves
merge(arr, startI,m, endI);
}
}
public static void merge(int arr[], int startI, int midpoint, int endI){
// Find sizes of two subarrays to be merged
int n1 = midpoint - startI + 1;
int n2 = endI - midpoint;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[startI + i];
for (int j=0; j<n2; ++j)
R[j] = arr[midpoint + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = startI;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
In the divide routine the Arrays.copyOfRange the to argument is exclusive meaning it wont include the to index in the result. Similarly, In the merge routine you have to use 2 variables to iterate the 2 arrays and I have changed <= to < in most places because IMO that looks clean.
import java.util.Arrays;
class Solution {
private static int[] mergeAndDivide(int[] array) {
if (array.length < 2) return array;
int[] arrayOne = Arrays.copyOfRange(array, 0, ((array.length - 1) / 2) + 1); // the final index is exclusive meaning it will not be included in the bisected array
int[] arrayTwo = Arrays.copyOfRange(array, ((array.length - 1) / 2 + 1), array.length);
arrayOne = mergeAndDivide(arrayOne);
arrayTwo = mergeAndDivide(arrayTwo);
return merge(arrayOne, arrayTwo);
}
private static int[] merge(int[] arrayOne, int[] arrayTwo) {
int[] arrayMerged = new int[arrayOne.length + arrayTwo.length];
int i = 0;
int j = 0;
while (i < arrayOne.length && j < arrayTwo.length) { // you need 2 variables to index first and second array;
if (arrayOne[i] > arrayTwo[j]) {
arrayMerged[i + j] = arrayTwo[j];
j++;
} else {
arrayMerged[i + j] = arrayOne[i];
i++;
}
}
while (i < arrayOne.length) {
arrayMerged[i + j] = arrayOne[i];
i++;
}
while (j < arrayTwo.length) {
arrayMerged[i + j] = arrayTwo[j];
j++;
}
return arrayMerged;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(mergeAndDivide(new int[]{3, 4, 5, 6, 1})));
}
}
Result : [1, 3, 4, 5, 6]
The second argument of Arrays.copyOfRange() is the index of the first element after the end of the slice. Use array.length / 2 for that and use the same value as the start index for the second slice.
Similarly, use < and do not adjust the lengths in the merge method. There is another mistake: you use the same index i into arrayOne, arrayTwo and arrayMerged, you should use a different index into each of the argument arrays and into the merged array.
Here is a modified version:
private int[] mergeAndDivide(int[] array) {
if (array.length < 2)
return array;
int[] arrayOne = Arrays.copyOfRange(array, 0, array.length / 2);
int[] arrayTwo = Arrays.copyOfRange(array, array.length / 2, array.length);
arrayOne = mergeAndDivide(arrayOne);
arrayTwo = mergeAndDivide(arrayTwo);
return merge(arrayOne, arrayTwo);
}
private int[] merge(int[] arrayOne, int[] arrayTwo) {
int[] arrayMerged = new int[arrayOne.length + arrayTwo.length];
int i = 0, j = 0, k = 0;
while (i < arrayOne.length && j < arrayTwo.length) {
if (arrayOne[i] <= arrayTwo[j])
arrayMerged[k++] = arrayOne[i++];
else
arrayMerged[k++] = arrayTwo[j++];
}
while (i < arrayOne.length) {
arrayMerged[k++] = arrayOne[i++];
}
while (j < arrayTwo.length) {
arrayMerged[k++] = arrayTwo[j++];
}
return arrayMerged;
}
There is a 2D array. int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}} . I want to get summation of each columns and get the maximum number. Finally it should be returned {5,7,8,9} . Because it has the maximum summation. I have mentioned i tried code below and it not return correct value. Help me to solve this
Your k is supposed to track the index with the greatest sum. So when you are resetting max you need to say k=i. You said i=k by mistake. Changing it makes your program run as desired.
EDIT: There was once code in the original question, to which this solution referred.
If the max column is expected, then I might have a solution:
import java.util.Arrays;
public class ArrayTest {
public static void main(String args[]) {
/*
* 1 3 4 1
* 5 7 8 9
* 6 1 2 1
*
*/
int[][] arr = {{1, 3, 4, 1}, {5, 7, 8, 9}, {6, 1, 2, 1}};
int m = arr.length;
int n = arr[0].length;
int[] arr2 = new int[n];
int p = 0;
int[][] colArray = new int[n][m];
for (int i = 0; i < n; i++) {
int[] arr_i = new int[m];
//System.out.println("i = " + i);
//System.out.println("p = " + p);
int sum = 0;
for (int j = 0; j < m; j++) {
arr_i[j] = arr[j][p];
sum += arr_i[j];
}
//System.out.println("Col: " + p + " : " + Arrays.toString(arr_i));
colArray[i] = arr_i;
arr2[p] = sum;
p++;
}
System.out.println("Sum: " + Arrays.toString(arr2));
int k = 0;
int max = arr2[0];
for (int i = 0; i < 3; i++) {
if (arr2[i] > max) {
max = arr2[i];
k = i;
}
}
System.out.println("Column index for max: " + k);
System.out.println("Column: " + Arrays.toString(colArray[k]));
}
}
Output:
Sum: [12, 11, 14, 11]
Column index for max: 2
Column: [4, 8, 2]
I recommend you find a way to break down your problem into smaller parts, solve each part with a function, then combine everything into a solution.
Example solution below:
public class Main {
public static long sum(int[] a){
long sum = 0;
for (int i : a) {
sum = sum + i;
}
return sum;
}
public static int[] withMaxSumOf(int[][] as){
// keep one sum for each array
long[] sums = new long[as.length];
// calculate sums
for (int i = 0; i < as.length; i++) {
int[] a = as[i];
sums[i] = sum(a);
}
// find the biggest one
int maxIndex = 0;
long maxSum = sums[0];
for (int i=1;i<sums.length;i++){
if (sums[i] > maxSum){
maxSum = sums[i];
maxIndex = i;
}
}
// return array that had biggest sum
return as[maxIndex];
}
public static void main(String[] args){
int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}};
// find the one with max sum
int[] max = withMaxSumOf(arr);
// print it
for (int i = 0; i < max.length; i++) {
int x = max[i];
if (i > 0) System.out.print(", ");
System.out.print(x);
}
System.out.println();
}
}
I think this might be your problem:
for(int i=0;i<3;i++) {
if(arr2[i]>max) {
max=arr2[i];
i=k;
}
}
I think that i=k really needs to be k=i.
Note also that it's worthwhile using better variable names. index instead of i, for instance. What is k? Call it "indexForHighestSum" or something like that. It doesn't have to be that long, but k is a meaningless name.
Also, you can combine the summation loop with the find-highest loop.
In the end, I might write it like this:
public class twoDMax {
public static void main(String args[]) {
int[][] arr= { {1,3,4,1}, {5,7,8,9}, {6,1,2,1} };
int indexForMaxRow = 0;
int previousMax = 0;
for(int index = 0; index < 4; ++index) {
int sum = 0;
for(int innerIndex = 0; innerIndex < 4; ++innerIndex) {
sum += arr[index][innerIndex];
}
if (sum > previousMax) {
previousMax = sum;
indexForMaxRow = index;
}
System.out.println(indexForMaxRow);
for(int index = 0; index < 4; ++index) {
System.out.println(arr[indexForMaxRow][index]);
}
}
}
I did a few other stylish things. I made use of more obvious variable names. And I am a little nicer about whitespace, which makes the code easier to read.
public static void main( String args[] ) {
int[][] arr = { { 1, 3, 4, 1 }, { 5, 7, 8, 9 }, { 6, 1, 2, 1 } };
int indexOfMaxSum = 0;
int maxSum = 0;
for ( int i = 0; i < arr.length; i++ ) {
int[] innerArr = arr[ i ]; // grab inner array
int sum = 0; // start sum at 0
for ( int j : innerArr ) {
// iterate over each int in array
sum += j; // add each int to sum
}
if ( sum > maxSum ) {
// if this sum is greater than the old max, store it
maxSum = sum;
indexOfMaxSum = i;
}
}
System.out.println( String.format( "Index %d has the highest sum with a sum of %d", indexOfMaxSum, maxSum ) );
int [] arrayWithLargestSum = arr[indexOfMaxSum]; // return me
}
Problem: Given K sorted arrays of size N each, merge them and print the sorted output.
Sample Input-1:
K = 3, N = 4
arr[][] = { {1, 3, 5, 7},
{2, 4, 6, 8},
{0, 9, 10, 11}} ;
Sample Output-1:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
I know there is a way to do this problem using a priority queue/min heap, but I want to do it using the merge procedure from mergeSort. The idea seems straightforward enough...at each iteration, merge the remaining arrays in groups of two, such that the number of arrays gets halved at each iteration.
However, whenever halving leads to an odd number, this becomes problematic.
My idea is that whenever halving leads to an odd number, we take care of the extra array by merging it with the array formed from the last merge.
The code I have so far is below. This only works on one out of 30 test cases, however:
static int[] mergeArrays(int[][] arr) {
int k = arr.length;
int n = arr[0].length;
if(k < 2){
return arr[0];
}
boolean odd_k;
if(k%2){
odd_k = false;
}
else{
odd_k = true;
}
while(k > 1){
int o;
if(odd_k){
o = (k/2) + 1;
}
else{
o = k/2;
}
int[][] out = new int[o][];
for(int i=0; i < k; i = i + 2){
int[] a;
int[] b;
if(odd_k && i == (k-1)){
b = arr[i];
b = out[i-1];
}
else{
a = arr[i];
b = arr[i+1];
}
out[i] = mergeTwo(a, b);
}
k = k/2;
if(k % 2 == 0){
odd_k = false;
}
else{
odd_k = true;
}
arr = out;
}
return arr[0];
}
static int[] mergeTwo(int[] a, int[] b){
int[] c = new int[a.length + b.length];
int i, j, k;
i = j = k = 0;
while(i < a.length && j < b.length){
if(a[i] < b[j]){
c[k] = a[i];
i++;
k++;
}
else{
c[k] = b[j];
j++; k++;
}
}
if(i < a.length){
while(i < a.length){
c[k] = a[i];
i++; k++;
}
}
if(j < b.length){
while(j < b.length){
c[k] = b[j];
j++; k++;
}
}
return c;
}
We can shorten your mergeTwo implementation,
static int[] mergeTwo(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int i = 0, j = 0, k = 0; // declare and initialize on one line
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
c[k++] = a[i++]; // increment and assign
} else {
c[k++] = b[j++]; // increment and assign
}
}
// No need for extra if(s)
while (i < a.length) {
c[k++] = a[i++];
}
while (j < b.length) {
c[k++] = b[j++];
}
return c;
}
And we can then fix your mergeArrays and shorten it by starting with the first row from the int[][] and then using mergeTwo to concatenate the arrays iteratively. Like,
static int[] mergeArrays(int[][] arr) {
int[] t = arr[0];
for (int i = 1; i < arr.length; i++) {
t = mergeTwo(t, arr[i]);
}
return t;
}
I then tested it with
public static void main(String[] args) {
int arr[][] = { { 1, 3, 5, 7 }, { 2, 4, 6, 8 }, { 0, 9, 10, 11 } };
System.out.println(Arrays.toString(mergeArrays(arr)));
}
And I get (as expected)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
As you say you have merged two arrays at a time. As it is inefficient you can merge all subarrays same time. What you have to do is to find the minimum from every subarray and remember the position of that element.
To do that we can use another array (say curPos) to remember the current position
private int[] merge(int[][] arr)
{
int K = arr.length;
int N = arr[0].length;
/** array to keep track of non considered positions in subarrays **/
int[] curPos = new int[K];
/** final merged array **/
int[] mergedArray = new int[K * N];
int p = 0;
while (p < K * N)
{
int min = Integer.MAX_VALUE;
int minPos = -1;
/** search for least element **/
for (int i = 0; i < K; i++)
{
if (curPos[i] < N)
{
if (arr[i][curPos[i]] < min)
{
min = arr[i][curPos[i]];
minPos = i;
}
}
}
curPos[minPos]++;
mergedArray[p++] = min;
}
return mergedArray;
Probably the easiest way to handle this is to use a queue of arrays. Initially, add all the arrays to the queue. Then, remove the first two arrays from the queue, merge them, and add the resulting array to the queue. Continue doing that until there is only one array in the queue. Something like:
for each array in list of arrays
queue.push(array)
while queue.length > 1
a1 = queue.pop()
a2 = queue.pop()
a3 = merge(a1, a2)
queue.push(a3)
result = queue.pop()
That simplifies things quite a bit, and the problem of "halving" goes away.
I have wrote a program to shift an int array left, but cannot find a way to move it right. Could you take a look at my code and comment if you have any ideas how how to "rotate" my array right based on the number of spaces (int x), as currently it only moves left. Thanks
public void makeRight(int x) {
int[] anArray = {0, 1, 2, 3, 4, 5};
int counter = 0;
while (counter < x) {
int temp = anArray[0];
for (int i = 0; i < anArray.length - 1; i++) {
anArray[i] = anArray[i + 1];
}
anArray[anArray.length - 1] = temp;
counter++;
}
for (int i = 0; i < anArray.length; i++){
System.out.print(anArray[i] + " ");
}
}
Rotate an array right
public void makeRight( int x )
{
int[] anArray =
{ 0, 1, 2, 3, 4, 5 };
int counter = 0;
while ( counter < x )
{
int temp = anArray[anArray.length - 1];
for ( int i = anArray.length - 1; i > 0; i-- )
{
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
for ( int i = 0; i < anArray.length; i++ )
{
System.out.print( anArray[i] + " " );
}
}
while (counter < x) {
int temp = anArray[anArray.length - 1];
for (int i = anArray.length - 1; i > 0; i--) {
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
in my opinion basically you had done on most of the parts to rotate an array (right).
Just that the concept of
anArray[i] = secondArray[(i + x) % anArray.length];
And
anArray[(i + x) % anArray.length] = secondArray[i];
is a bit different.
There would be something like this
int[] anArray = {0, 1, 2, 3, 4, 5};
//int counter = 0;
//int x = 2;
int[] secondArray = new int[anArray.length];
for (int i = 0; i < anArray.length; i++) {
secondArray[(i + x) % anArray.length] = anArray[i];
}
for (int i = 0; i < secondArray.length; i++){
System.out.print(secondArray[i] + " ");
}
As for how the "%" works, Codility - CyclicRotation this link should had a clear explanation.
Below function can help you
public static void rightRotateArray(int[] a, int requiredIterations) {
// right-rotate [a] by k moves
// totalActiveIterations by MOD
// => because every n(a.length) rotations ==> we receive the same array
int totalActiveIterations = requiredIterations % a.length;
for (int i = 0; i < totalActiveIterations; i++) {
// make lastElement as BKP temp
int temp = a[a.length - 1];
// make other elements => each one equal previous one [starting by lastElement]
for (int j = (a.length - 1); j >= 1; j--) {
a[j] = a[j - 1];
}
// make 1stElement equal to (BKP as temp = lastElement)
a[0] = temp;
}
}
Something like this should work
private void shiftArrayRight() {
int endElementvalue = element[element - 1];
int[] startElements = Arrays.copyOfRange(element, 0 , element.length - 1);
element[0] = endElementvalue;
for(int i = 0, x = 1; i < startElements.length; i++, x++) {
element[x] = startElements[i];
}
System.out.println(Arrays.toString(element);
}
The other answers are merely code dumps, with zero explanations. Here's an algorithm I came up with:
We rotate the array in place. Observe that the target position of every element is given by (index + k) modulo size. For range 0 to k - 1, we recursively swap each element with the one in its target position as long as the target position is greater than the current position. This is because since we are incrementally progressing from lower to higher indices, a smaller target index indicates that the corresponding element had already been swapped.
Example:
Rotate [1, 2, 3, 4, 5, 6] by 3
Index to target index:
0 to 3
1 to 4
2 to 5
3 to 0
4 to 1
5 to 2
swap(0, 3) => [4, 2, 3, 1, 5, 6]
swap(0, 0) => return
swap(1, 4) => [4, 5, 3, 1, 2, 6]
swap(1, 1) => return
swap(2, 5) => [4, 2, 6, 1, 2, 3]
swap(2, 2) => return
Done!
Another example:
Rotate [2, 3, 4, 1] by 1
Index to target index:
0 to 1
1 to 2
2 to 3
3 to 0
swap(0, 1) => [3, 2, 4, 1]
swap(0, 2) => [4, 2, 3, 1]
swap(0, 3) => [1, 2, 3, 4]
swap(3, 0) => return
Done!
Code:
static void rotateRight(int[] xs, int k) {
swap(0, 0, xs, k);
}
private static void swap(int original, int current, int[] xs, int k) {
int target = (original + k) % xs.length;
if (target > current) {
int tmp = xs[current];
xs[current] = xs[target];
xs[target] = tmp;
swap(target, current, xs, k);
}
}
public static List<int> rotateLeft(int d, List<int> arr)
{
int listSize = arr.Count();
int[] newArr = new int[listSize];
for(int oldIndex=0; oldIndex< listSize; oldIndex++)
{
int newIndex = (oldIndex + (listSize - d))% listSize;
newArr[newIndex] = arr[oldIndex];
}
List<int> newList = new List<int>(newArr);
return newList;
}
the easiest way is to use c++ 11 and above, in Codility test for Cyclicrotation.
imagine doing it in earlier versions, Duh!
#include <algorithm>
#include <iterator>
vector<int> solution(vector<int> &A, int K) {
if (A.size() == 0) {
return A;
}
for (int i=0;i<K;i++) {
//Create auciliary array
std::vector<int> aux(A.size());
//copy array to be rotated there by means of C++11
std::copy(std::begin(A), std::end(A), std::begin(aux));
//insert last element from aux to begining of the array
A.insert(A.begin(), aux.end()-1, aux.end());
//remove last element which is already become first
A.pop_back();
}
return A;
}
Just change the code like this
public void makeRight(int x) {
int[] anArray = {0, 1, 2, 3, 4, 5};
int counter = 0;
while(counter< x){
int temp = anArray[anArray.length - 1];
for (int i = anArray.length - 1; i > 0; i--) {
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
for (int i = 0; i < anArray.length; i++)
System.out.print(anArray[i] + " ");
}