Find element at given index after a number of rotations - java

Input : arr[] : {1, 2, 3, 4, 5}
ranges[] = { {0, 2}, {0, 3} }
index : 1
Output : 3
Explanation : After first given rotation {0, 2}
arr[] = {3, 1, 2, 4, 5}
After second rotation {0, 3}
arr[] = {4, 3, 1, 2, 5}
After all rotations we have element 3 at given index 1.
Not Able to Understand Why starting from last rotation gives right result but if we start from rotation 0 to last in loop it gives wrong result???
https://www.geeksforgeeks.org/find-element-given-index-number-rotations/
// Java code to rotate an array
// and answer the index query
import java.util.*;
class GFG
{
// Function to compute the element at
// given index
static int findElement(int[] arr, int[][] ranges,
int rotations, int index)
{
for (int i = rotations - 1; i >= 0; i--) {
// Range[left...right]
int left = ranges[i][0];
int right = ranges[i][1];
// Rotation will not have any effect
if (left <= index && right >= index) {
if (index == left)
index = right;
else
index--;
}
}
// Returning new element
return arr[index];
}
// Driver
public static void main (String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
// No. of rotations
int rotations = 2;
// Ranges according to 0-based indexing
int[][] ranges = { { 0, 2 }, { 0, 3 } };
int index = 1;
System.out.println(findElement(arr, ranges,
rotations, index));
}
}
This will give right result but following will produce wrong result.
for (int i = 0; i < rotations; i++) {
// Range[left...right]
int left = ranges[i][0];
int right = ranges[i][1];
// Rotation will not have any effect
if (left <= index && right >= index) {
if (index == left)
index = right;
else
index--;
}
}

Lets us consider given 5 length array A1.
You have applied {0,2} rotation on A1. It is changed to A2.
You have applied {0,3} rotation on A2.. It is changed to A3
Now you are looking for output index 1 in A3 (which is {0,3} rotated on A2).
So Index 1 in A3 = Index 0 in A2 (as per the logic)
Now you are looking for Index 0 in A2 (which is {0,2} rotated on A1)
So Index 0 in A2 = Index 2 in A1 (as per the logic)
Hope this explanation clears why the rotations array is iterated in reverse way.

Not Able to Understand Why starting from last rotation gives right
result but if we start from rotation 0 to last in loop it gives wrong
result???
Because its not supposed to give the same output. The final results depends on the order in which you apply the rotations.
Suppose first you apply {0,3}, the array would be :
4 , 1 , 2 , 3 , 5
Now you apply {0,2}
2 , 4 , 1 , 3 , 5
Clearly the element at index 1 is NOT 3

Related

How to shift everything in a 2D array to the left

I need to take a 2D array and move everything as far left as possible. It is a 4x4 array and I have tried to do it but either only move certain items or the index goes out of bounds.
The gameBoard array looks like this:
{0 2 4 2}
{0 0 2 0}
{2 2 0 0}
{0 4 0 2}
and after you call the swipeLeft() method it should look like this:
{2 4 2 0}
{2 0 0 0}
{2 2 0 0}
{4 2 0 0}
There is also the issue of placing a zero into the previous index that you moved it from.
I created a double for loop to just loop through the array and tried to code something that would move it over but it hasn't worked.
Here was the code I had so far
public void swipeLeft() {
for ( int r = 0; r < gameBoard.length; r++ ) {
for ( int c = 0; c < gameBoard[r].length; c++ ) {
gameBoard[r][c] = gameBoard[r][ (c+1) %
gameBoard.length];
}
}
}
Based on your desired OUTPUT, it looks like swipeLeft() is supposed to push all non-zero values to the very left of their row, displacing the zeroes to the right of all non-zero values.
If that's correct, this is similar to Old Dog Programmer's approach, except all shifting is done "in place" without creating any new arrays:
import java.util.*;
class Main {
private static int[][] gameBoard;
public static void main(String[] args) {
gameBoard = new int[][] {
{0, 2, 4, 2},
{0, 0, 2, 0},
{2, 2, 0, 0},
{0, 4, 0, 2}
};
System.out.println("Before:");
displayBoard();
swipeLeft();
System.out.println("\nAfter:");
displayBoard();
}
public static void displayBoard() {
for(int[] row : gameBoard) {
System.out.println(Arrays.toString(row));
}
}
public static void swipeLeft() {
for(int[] row : gameBoard) {
// find the first blank (zero) spot
int nextIndex = 0;
while(nextIndex < row.length && row[nextIndex] != 0) {
nextIndex++;
}
// start with the first blank, and shift any non-zero
// values afterwards to the left
for(int col=nextIndex; col < row.length; col++) {
if (row[col] != 0) {
row[nextIndex] = row[col];
row[col] = 0;
nextIndex++;
}
}
}
}
}
Output:
Before:
[0, 2, 4, 2]
[0, 0, 2, 0]
[2, 2, 0, 0]
[0, 4, 0, 2]
After:
[2, 4, 2, 0]
[2, 0, 0, 0]
[2, 2, 0, 0]
[4, 2, 0, 0]
From the example in the question, it appears to me that what is wanted is to shift all non-zero elements to the left, and zero elements are shifted to the right. The order of the non-zero elements is to be retained.
Note that each row is independent of other rows.
One way to approach this is to create a method that works on a 1D array. This method takes a 1D array as a parameter, and returns another 1D array with the elements shifted:
public static int [] zeroShift (int [] arr) {
int [] left = new int [arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
left [count++] = arr [i];
}
}
return left;
}
This copies each non-zero element to a new array of the same size, keeping track (count) of how many have been copied so far. Note this relies on left being initialized to all-zeros.
Once that method is working, it can be used for gameBoard on a row-by-row basis:
public void swipeLeft() {
for (int r = 0; r < gameBoard.length; r++) {
gameBoard [r] = zeroShift (gameBoard [r]);
}
// output for testing
for (int i = 0; i < gameBoard.length; ++i) {
System.out.println(Arrays.toString(gameBoard[i]));
}
}
To rotate the array in place, you should roteate the array 3 times:
123456 -> 654312
654321
3456..
....12
public static void shiftLeft(int[] arr, int offs) {
if (offs <= 0)
return;
offs = arr.length - offs % arr.length - 1;
for (int i = 0, j = arr.length - 1; i < j; i++, j--)
swap(arr, i, j);
for (int i = 0, j = offs; i < j; i++, j--)
swap(arr, i, j);
for (int i = offs + 1, j = arr.length - 1; i < j; i++, j--)
swap(arr, i, j);
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
So your code intends to rotate the board one column to the left. Rotate? Well, the numbers you push out on the left might come back on the end, right?
Probably the line
gameBoard[r][c] = gameBoard[r][ (c+1) % gameBoard.length];
should be
gameBoard[r][c] = gameBoard[r][ (c+1) % gameBoard[r].length];
But try to do this stuff with pen & paper, and you should notice that you are going to loose one column/copy the values from the second column into the first, then copy that into the last column again.
You will need to change two items:
store the value from the first column somewhere if you still need it so you can push it into the last one.
only rotate the column data if it needs to be rotated. Or in other words, rotate the remainder of the row if you find a zero. In this case you do not need to remember the first column, as you will overwrite a zero and push a zero into the last column. And then it would not be called rotate but shift.
Exercise this with pen & paper until you can write down instructions for someone else to perform the same operation. Then you are ready to also write it in Java.

Maximize the number of Elements in the Array divisible by M

I'm working on the following task.
Given an array of n integers and two integer numbers m and k.
You can add any positive integer to any element of the array such that
the total value does not exceed k.
The task is to maximize the
multiples of m in the resultant array.
Consider the following example.
Input:
n = 5, m = 2, k = 2, arr[] = [1, 2, 3, 4, 5]
Let's add 1 to the element arr[0] and 1 to arr[2] then the final array would be:
[2, 2, 4, 4, 5]
Now there are four (4) elements which are multiples of m (2).
I am not getting correct output.
My code:
public class Main {
public static void main(String[] args) {
int n = 5;
int m = 4;
int k = 3;
int count = 0;
int[] arr = {17, 8, 9, 1, 4};
for (int i = 0; i < n; i++) {
for (int j = 0; j <= k; j++) {
// check initial
if (arr[i] % m == 0) {
break;
}
// add
arr[i] = arr[i] + j;
// check again
if (arr[i] % m == 0) {
count++;
break;
}
}
}
System.out.println("Final Array : " + Arrays.toString(arr));
System.out.println("Count : " + count);
}
}
This task boils down to a well-known Dynamic programming algorithm called Knapsack problem after a couple of simple manipulations with the given array.
This approach doesn't require sorting and would be advantages when k is much smaller n.
We can address the problem in the following steps:
Iterate over the given array and count all the numbers that are already divisible by m (this number is stored in the variable count in the code below).
While iterating, for every element of the array calculate the difference between m and remainder from the division of this element by m. Which would be equal to m - currentElement % m. If the difference is smaller or equal to k (it can cave this difference) it should be added to the list (differences in the code below) and also accumulated in a variable which is meant to store the total difference (totalDiff). All the elements which produce difference that exceeds k would be omitted.
If the total difference is less than or equal to k - we are done, the return value would be equal to the number of elements divisible by m plus the size of the list of differences.
Otherwise, we need to apply the logic of the Knapsack problem to the list of differences.
The idea behind the method getBestCount() (which is an implementation Knapsack problem) boils down to generating the "2D" array (a nested array of length equal to the size of the list of differences +1, in which every inner array having the length of k+1) and populating it with maximum values that could be achieved for various states of the Knapsack.
Each element of this array would represent the maximum total number of elements which can be adjusted to make them divisible by m for the various sizes of the Knapsack, i.e. number of items available from the list of differences, and different number of k (in the range from 0 to k inclusive).
The best way to understand how the algorithm works is to draw a table on a piece of paper and fill it with numbers manually (follow the comments in the code, some intermediate variables were introduced only for the purpose of making it easier to grasp, and also see the Wiki article linked above).
For instance, if the given array is [1, 8, 3, 9, 5], k=3 and m=3. We can see 2 elements divisible by m - 3 and 9. Numbers 1, 8, 5 would give the following list of differences [2, 1, 1]. Applying the logic of the Knapsack algorithm, we should get the following table:
[0, 0, 0, 0]
[0, 0, 1, 1]
[0, 1, 1, 2]
[0, 1, 2, 2]
We are interested in the value right most column of the last row, which is 2 plus 2 (number of elements divisible by 3) would give us 4.
Note: that code provided below can dial only with positive numbers. I don't want to shift the focus from the algorithm to such minor details. If OP or reader of the post are interested in making the code capable to work with negative number as well, I'm living the task of adjusting the code for them as an exercise. Hint: only a small change in the countMultiplesOfM() required for that purpose.
That how it might be implemented:
public static int countMultiplesOfM(int[] arr, int k, int m) {
List<Integer> differences = new ArrayList<>();
int count = 0;
long totalDiff = 0; // counter for the early kill - case when `k >= totalDiff`
for (int next : arr) {
if (next % m == 0)
count++; // number is already divisible by `m` we can increment the count and from that moment we are no longer interested in it
else if (m - next % m <= k) {
differences.add(m - next % m);
totalDiff += m - next % m;
}
}
if (totalDiff <= k) { // early kill - `k` is large enough to adjust all numbers in the `differences` list
return count + differences.size();
}
return count + getBestCount(differences, k); // fire the rest logic
}
// Knapsack Algorithm implementation
public static int getBestCount(List<Integer> differences, int knapsackSize) {
int[][] tab = new int[differences.size() + 1][knapsackSize + 1];
for (int numItemAvailable = 1; numItemAvailable < tab.length; numItemAvailable++) {
int next = differences.get(numItemAvailable - 1); // next available item which we're trying to place to knapsack to Maximize the current total
for (int size = 1; size < tab[numItemAvailable].length; size++) {
int prevColMax = tab[numItemAvailable][size - 1]; // maximum result for the current size - 1 in the current row of the table
int prevRowMax = tab[numItemAvailable - 1][size]; // previous maximum result for the current knapsack's size
if (next <= size) { // if it's possible to fit the next item in the knapsack
int prevRowMaxWithRoomForNewItem = tab[numItemAvailable - 1][size - next] + 1; // maximum result from the previous row for the size = `current size - next` (i.e. the closest knapsack size which guarantees that there would be a space for the new item)
tab[numItemAvailable][size] = Math.max(prevColMax, prevRowMaxWithRoomForNewItem);
} else {
tab[numItemAvailable][size] = Math.max(prevRowMax, prevColMax); // either a value in the previous row or a value in the previous column of the current row
}
}
}
return tab[differences.size()][knapsackSize];
}
main()
public static void main(String[] args) {
System.out.println(countMultiplesOfM(new int[]{17, 8, 9, 1, 4}, 3, 4));
System.out.println(countMultiplesOfM(new int[]{1, 2, 3, 4, 5}, 2, 2));
System.out.println(countMultiplesOfM(new int[]{1, 8, 3, 9, 5}, 3, 3));
}
Output:
3 // input array [17, 8, 9, 1, 4], m = 4, k = 3
4 // input array [1, 2, 3, 4, 5], m = 2, k = 2
4 // input array [1, 8, 3, 9, 5], m = 3, k = 3
A link to Online Demo
You must change 2 line in your code :
if(arr[i]%m==0)
{
count++; // add this line
break;
}
// add
arr[i]=arr[i]+1; // change j to 1
// check again
if(arr[i]%m==0)
{
count++;
break;
}
The first is because the number itself is divisible.
and The second is because you add a number to it each time.That is wrong.
for example chenge your arr to :
int[] arr ={17,8,10,2,4};
your output is :
Final Array : [20, 8, 16, 8, 4]
and That is wrong because 16-10=6 and is bigger than k=3.
I believe the problem is that you aren't processing the values in ascending order of the amount by which to adjust.
To solve this I started by using a stream to preprocess the array. This could be done using other methods.
map the values to the amount to make each one, when added, divisible by m.
filter out those that equal to m' (already divisible by m`)
sort in ascending order.
Once that is done. Intialize max to the difference between the original array length and the processed length. This is the number already divisible by m.
As the list is iterated
check to see if k > amount needed. If so, subtract from k and increment max
otherwise break out of the loop (because of the sort, no value remaining can be less than k)
public static int maxDivisors(int m, int k, int[] arr) {
int[] need = Arrays.stream(arr).map(v -> m - v % m)
.filter(v -> v != m).sorted().toArray();
int max = arr.length - need.length;
for (int val : need) {
if (k >= val) {
k -= val;
max++;
} else {
break;
}
}
return max;
}
int m = 4;
int k = 3;
int[] arr ={17,8,9,1,4};
int count = maxDivisors(m, k, arr);
System.out.println(count);
prints
3

Square Value at Index without using a temp array

At 0th index value is 4, so I have to check the value at index 4 and square it and place the value at 0th index without using a temp array:
Index 0 1 2 3 4
Values 4 3 1 2 0
================
Result 0 4 9 1 16
Now I am getting the first two values right, but the last three are not right. My code is as below:
static void Index(int arr[], int n) {
for(int i=0;i<n;i++) {
int index = arr[i];
int value = arr[index];
arr[i]=value*value;
}
}
Below is the output that I am getting:
Original Array
4 3 1 2 0
Array after Squaring
0 4 16 256 0
Can anyone help me out here as to what am I doing wrong?
Assuming the numbers are within range [0, 46341), we can store both the old and the new values in the array during the process (as 32 bits are enough). Then after the first loop we do another one to discard the old values and square the new ones.
// assume array[i] is within range [0, 46341) for any i
static void f(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = array[i] & 0xffff; // get old value
array[i] = array[j] << 16 | j; // put new and old values
}
for (int i = 0; i < array.length; i++) {
int j = array[i] >>> 16; // get new value
array[i] = j * j; // put new value squared
}
}
NOTE: This approach is valid only if length of array is less than 10.
I have completed this code using only one loop without using any extra space.
Although, I have set a flag to run the complete loop twice.
If you do not have any constraint of using one loop, you can avoid using the flag and simply use two loops.
Approach:
Index 0 1 2 3 4
Values 4 3 1 2 0
Updated value 04 23 31 12 40
You must have got the idea what I did here.
I put the values at tens place whose square is to be displayed.
Now you have to just have to iterate once more and put the square of tens place at that index
Here's the code:
void sq(int arr[], int n){
bool flag = false;
for(int i=0; i<n; i++){
if(!flag){
if(arr[arr[i]] < 10){
arr[i] += (arr[arr[i]] * 10);
}
else{
arr[i] += ((arr[arr[i]]%10) * 10);
}
}
if(i==n-1 && !flag){
i=0;
flag = true;
}
if(flag)
arr[i] = (arr[i]/10) * (arr[i]/10);
}
}
It is in C++.
The problem is you are changing the values in your original array. In you current implementation this is how your array changes on each iteration:
{4, 3, 1, 2, 0}
{0, 3, 1, 2, 0}
{0, 4, 1, 2, 0}
{0, 4, 16, 2, 0}
{0, 4, 16, 256, 0}
The problem is you still need the values stored in the original array for each iteration. So the solution is to leave the original array untouched and put your values into a new array.
public static void index(int arr[]) {
int[] arr2 = new int[arr.length];
for(int i=0;i<arr.length;i++) {
int index = arr[i];
int value = arr[index];
arr2[i]=value*value;
}
}
Values of arr2 in revised process:
{0, 0, 0, 0, 0}
{0, 0, 0, 0, 0}
{0, 4, 0, 0, 0}
{0, 4, 9, 0, 0}
{0, 4, 9, 1, 0}
{0, 4, 9, 1, 16}

Counting down a variable length array of integers to Zero in Java

I have an array that contains the total number of lines in 3 files. Example: [3,4,5]. I would like to produce a sequence of numbers that count that array down to zero in a methodical way giving me every combination of lines in the three files. This example uses 3 files/length-3 array, but the algorithm should be able to work an array with any arbitrary length.
For the example above, the solution would look like:
[3,4,5] (line 3 from file 1, line 4 from file 2, line 5 from file 3)
[3,4,4]
[3,4,3]
[3,4,2]
[3,4,1]
[3,4,0]
[3,3,5]
[3,3,4]
[3,3,3]
[3,3,2]
and so on...
My first attempt at producing an algorithm for this recursively decrements a position in the array, and when that position reaches zero - decrements the position before it. However I'm not able to keep the decrementing going for farther than the last two positions.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FilePositionGenerator {
public static void main(String[] args) {
int[] starterArray = {2, 2, 2};
int[] counters = starterArray.clone();
List<Integer> results = new ArrayList<Integer>();
FilePositionGenerator f = new FilePositionGenerator();
f.generateFilePositions(starterArray, counters, (starterArray.length - 1), results);
}//end main
void generateFilePositions(int[] originalArray, int[] modifiedArray, int counterPosition, List<Integer> results) {
if (modifiedArray[counterPosition] == 0 && counterPosition > 0) {
modifiedArray[counterPosition] = originalArray[counterPosition];
counterPosition = counterPosition - 1;
} else {
modifiedArray[counterPosition] = modifiedArray[counterPosition] - 1;
System.out.println(Arrays.toString(modifiedArray));
generateFilePositions(originalArray, modifiedArray, counterPosition, results);
}
}
}
I understand that to deal with a variable length array, the algorithm must be recursive, but I'm having trouble thinking it through. So I decided to try a different approach.
My second attempt at producing an algorithm uses a dual pointer method that keeps a pointer on the current countdown position[the rightmost position], and a pointer to the next non-rightmost position(pivotPointer) that will be decremented when the rightmost position reaches zero. Like so:
import java.util.Arrays;
class DualPointer {
public static void main(String[] args) {
int[] counters = {2, 2, 2}; // initialize the problem set
int[] original = {2, 2, 2}; // clone a copy to reset the problem array
int[] stopConditionArray = {0, 0, 0}; // initialize an object to show what the stopCondition should be
int pivotLocation = counters.length - 1; // pointer that starts at the right, and moves left
int counterLocation = counters.length - 1; // pointer that always points to the rightmost position
boolean stopCondition = false;
System.out.println(Arrays.toString(counters));
while (stopCondition == false) {
if (pivotLocation >= 0 && counterLocation >= 0 && counters[counterLocation] > 0) {
// decrement the rightmost position
counters[counterLocation] = counters[counterLocation] - 1;
System.out.println(Arrays.toString(counters));
} else if (pivotLocation >= 0 && counters[counterLocation] <= 0) {
// the rightmost position has reached zero, so check the pivotPointer
// and decrement if necessary, or move pointer to the left
if (counters[pivotLocation] == 0) {
counters[pivotLocation] = original[pivotLocation];
pivotLocation--;
}
counters[pivotLocation] = counters[pivotLocation] - 1;
counters[counterLocation] = original[counterLocation]; // reset the rightmost position
System.out.println(Arrays.toString(counters));
} else if (Arrays.equals(counters, stopConditionArray)) {
// check if we have reached the solution
stopCondition = true;
} else {
// emergency breakout of infinite loop
stopCondition = true;
}
}
}
}
Upon running, you can see 2 obvious problems:
[2, 2, 2]
[2, 2, 1]
[2, 2, 0]
[2, 1, 2]
[2, 1, 1]
[2, 1, 0]
[2, 0, 2]
[2, 0, 1]
[2, 0, 0]
[1, 2, 2]
[1, 2, 1]
[1, 2, 0]
[0, 2, 2]
[0, 2, 1]
[0, 2, 0]
Number one, the pivotPointer does not decrement properly when the pivotPointer and currentCountdown are more than one array cell apart. Secondly, there is an arrayIndexOutOfBounds at the line counters[pivotLocation] = counters[pivotLocation] - 1; that if fixed,
breaks the algorithm from running properly alltogether.
Any help would be appreciated.
I'll suggest a different approach.
The idea in recursion is to reduce the size of the problem in each recursive call, until you reach a trivial case, in which you don't have to make another recursive call.
When you first call the recursive method for an array of n elements, you can iterate in a loop over the range of values of the last index (n-1), make a recursive call to generate all the combinations for the array of the first n-1 elements, and combine the outputs.
Here's some partial Java/ partial pseudo code :
The first call :
List<int[]> output = generateCombinations(inputArray,inputArray.length);
The recursive method List<int[]> generateCombinations(int[] array, int length) :
List<int[]> output = new ArrayList<int[]>();
if length == 0
// the end of the recursion
for (int i = array[length]; i>=0; i--)
output.add (i)
else
// the recursive step
List<int[]> partialOutput = generateCombinations(array, length - 1)
for (int i = array[length]; i>=0; i--)
for (int[] arr : partialOutput)
output.add(arr + i)
return output
The recursive method returns a List<int[]>. This means that in "output.add (i)" you should create an int array with a single element and add it to the list, while in output.add(arr + i) you'll create an array of arr.length+1 elements, and copy to it the elements of arr followed by i.
The fun thing about recursion is that you can have it do exactly what you want it to. In this case, for each number at index i of your array of counts, we want to combine it with each number at index i + 1 until we reach the end of the array. The trick is not to return to index i once you've run through all the options for it.
JavaScript code:
var arr = [3,4,5];
var n = arr.length;
function f(cs,i){
// base case
if (i == n){
console.log(cs.join(','));
return;
}
// otherwise
while (cs[i] >= 0){
// copy counts
_cs = cs.slice();
// recurse
f(_cs,i + 1);
// change number at index i
cs[i]--;
}
}
f(arr,0);

how to order Arrays value as circular format in java?

i have array values as like
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
suppose if i pass value "5" to tat array, it should be ordered as like
{"5","6","7","8","9","10",1","2","3","4"};...
how to do?plz anyone help?
thank u
What you need is called rotation. You can use Collections.rotate() method. Convert the array to a list and pass it to the method. This will rotate the array in place since the list is backed by the array:
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
Collections.rotate(Arrays.asList(value), 5);
The above code will rotate the array by a distance of 5. The resulting value array:
[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
Your question has two interpretations:
Rotate 5 steps, or
rotate the array so that 5 is the first element (regardless of where it is in the array).
Here is a solution for both alternatives:
import java.util.Arrays;
public class Test {
public static String[] rotateArray(String[] arr, int n) {
String[] rotated = new String[arr.length];
System.arraycopy(arr, n-1, rotated, 0, arr.length-n+1);
System.arraycopy(arr, 0, rotated, arr.length-n+1, n-1);
return rotated;
}
public static String[] rotateArrayTo(String[] arr, String head) {
for (int i = 0; i < arr.length; i++)
if (arr[i].equals(head))
return rotateArray(arr, i + 1);
throw new IllegalArgumentException("Could not find " + head);
}
public static void main(String[] args) {
String[] value = {"1","2","3","4","5","6","7","8","9","10"};
// Rotate so that it starts at 5:th element
value = rotateArray(value, 5);
System.out.println(Arrays.toString(value));
// Rotate so that it starts with element "7"
value = rotateArrayTo(value, "7");
System.out.println(Arrays.toString(value));
}
}
Output:
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4]
[7, 8, 9, 10, 1, 2, 3, 4, 5, 6]
(ideone.com link)
first find the index of the entered value from the array..
and then in a loop move from the index to the final position.. and store these values in a new array.
after that, in the same result array, store the values from index 0 to the index of the entered value - 1.
You really don't need to store the values in a different array. Just find the index [say idx] of the value passed. And then start a loop from the start of the array and swap the values starting from idx.
For example -
idx = [some-value]
while [idx < arr.length]
temp = arr[i]
arr[i] = arr[idx]
arr[idx] = t
idx += 1
i += 1
Update:
I stand corrected by #aioobe. I simply worked out something for the 5th index - my bad. Here's something that works, if in case, you want to stay away from library functions -
private void slideLeft(String[] arr)
{
String t = arr[arr.length - 1];
String temp = null;
int next = -1;
for (int i = arr.length - 1; i >= 0; i--)
{
next = ( i == 0 ) ? arr.length - 1 : i - 1;
temp = arr[next];
arr[next] = t;
t = temp;
}
}
you'll need to call this method the number of times you need to shift the array members.
note: O(n^2) alert. not suitable for large shifts/arrays.

Categories