EX: I have an array {1, 2, 3, 4, 5} and an integer number 7
It will rotate 7 spaces to the right like: {4, 5, 1, 2, 3}
I also have that array {1, 2, 3, 4, 5} and an integer number -7
It will rotate 7 spaces to the left like: {3, 4, 5, 1, 2}
I have rotated the array to the right by using:
for(int i = 0; i < data.length; i++){
result[(i+n) % data.length ] = data[i];
}
But how can we rotate an array to the left?
Rotating to the left by n is the same as rotating to the right by length-n.
Rotate right (for positive n):
for(int i = 0; i < data.length; i++){
result[(i+n) % data.length ] = data[i];
}
Rotate left (for positive n):
for(int i = 0; i < data.length; i++){
result[(i+(data.length-n)) % data.length ] = data[i];
}
This way you can avoid a modulo of a negative number.
If you want to input an integer n that rotates right if n is positive and left if n is negative, you can do it like this:
int[] rotateArray(int n, int[] data)
{
if(n < 0) // rotating left?
{
n = -n % data.length; // convert to +ve number specifying how
// many positions left to rotate & mod
n = data.length - n; // rotate left by n = rotate right by length - n
}
int[] result = new int[data.length];
for(int i = 0; i < data.length; i++){
result[(i+n) % data.length ] = data[i];
}
return result;
}
In case rotate to the left, you can use this to avoid a modulo of a negative number:
int[] data = {1, 2, 3, 4, 5};
int[] result = new int[data.length];
for (int i = 0; i < data.length; i++) {
result[(i + (data.length - 2)) % data.length] = data[i];
}
for (int i : result) {
System.out.println(i);
}
You may also use linkedlist to achieve the same.
Integer[] arr = {1,2,3,4,5};
LinkedList<Integer> ns = new LinkedList<Integer>(Arrays.asList(arr));
int rotate=3;
if(rotate<0)
rotate += arr.length;
List<Integer> leftlist = ns.subList(0, rotate);
List<Integer> rightlist = ns.subList(rotate, arr.length);
LinkedList<Integer> result = new LinkedList<Integer>();
result.addAll(rightlist);
result.addAll(leftlist);
System.out.println(result);
If you want to rotate an array named a[n] with n as the size of an array and d as the number of rotation (in your case d=7), you can use this code:
d = d % n;
for(int i=d;i<n;i++){
System.out.print(a[i]+" ");
}
for(int i=0;i<(d);i++){
System.out.print(a[i]+" ");
}
This code will print the array elements in order after the left rotation is performed. If you want you can store it in another array, or you can show array elements as shown in the above method.
Here is the complete java program for n left rotations of an array.
public class ArrayRotation {
private static Scanner sc;
public static void main(String[] args) {
int n,k;
sc = new Scanner(System.in);
System.out.print("Enter the size of array: ");
n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter the "+n+" elements in the list: ");
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
System.out.print("Enter the number of left shifts to array: ");
k = sc.nextInt();
System.out.print("Array before "+k+" shifts: ");
display(a);
solution(a,k);
System.out.println();
System.out.print("Array after "+k+" shifts: ");
display(a);
}
public static void solution(int[] a, int k){
int temp=0, j;
for(int i=0;i<k;i++){
temp = a[0];
// j=0; // both codes work i.e. for loop and while loop as well
// while(j<a.length-1){
// a[j]=a[j+1];
// j++;
// }
for(j=0;j<a.length-1;j++)
a[j]=a[j+1];
a[j]=temp;
}
}
public static void display(int[] a){
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
public static int[] arrayLeftRotation(int[] array, int elements, int rotations) {
// i = checks number of rotations
for (int i = 0; i < rotations; i++) {
int first = array[0];
int last = array[elements - 1];
// j = rotates each element
for (int j = 0; j < elements; j++) {
// check if at first index
if (j == 0) {
array[elements - 1] = first;
}
// check if at last index
if (j == (elements - 1)) {
// if at last index: make element in index before last = to last element
array[elements - 2] = last;
} else {
array[j] = array[j + 1];
}
}
}
return array;
}
This is the cleanest answer I could come up with.
Notice that you need to compute rotations % length so that your program is robust to a number of rotations greater than the size of your array.
static int[] rotateLeft(int[] arr, int rotations) {
int length = arr.length;
int[] result = new int[length];
rotations = rotations % length; // robust to rotations > length
int position = length - rotations; // compute outside the loop to increase performance
for (int i = 0; i < length; i++) {
result[(position + i) % length] = arr[i];
}
return result;
}
I used the below approach putting the array into a new array in its new position.
int length = a.length;
int[] newArr = new int[a.length];
for (int i = length - 1; i >= 0 ; i--){
int newPosition = i - d; // d is the number of rotation
if (newPosition < 0)
newPosition = length + newPosition;
newArr[newPosition] = a[i];
}
Initially i wanted to swap into the same array using the below approach but it did not work all the cases. For example where 2 array elements are being swapped due to rotation. So newPosition and position keep on pointing to each other. Hence rest of the array is not moved.
Not sure if it is possible to rotate array with O(n) complexity in the same array.
int length = a.length;
int position = length-1;
int temp = a[position];
for (int i = 0; i < length; i++){
int newPosition = position - d;
if (newPosition < 0)
newPosition = length + newPosition;
int cache = a[newPosition];
a[newPosition]= temp;
temp = cache;
position = newPosition;
}
Here is my solution in Javascript:
n is the number of elements and r is the number of rotations.
a is the array.
function rotate(a,r,n)}
for(var i = 0; i<r; i++){
var aa = array[0] //
for (var j = 0; j < n-1; j++){
array[j] = array[j+1] //
}
array[n-1] = aa //
}
return a
}
var array = [1,2,3,4,5];
console.log(rotate(array,1,5))
// Left rotation using lambda expression.
int [] ar = {1,6,7,5,9,1,34,7};
int shift =2;
int[] posAr = IntStream.range(0, ar.length).map(i->(ar[(i + (ar.length + shift)) % ar.length])).toArray();
//You can print the data
Arrays.stream(posAr).forEach(System.out::println);
enter image description here
Show code:
if(a.length==0 || a.length==1)
return a;
int r=d%a.length;
int A[]=new int[a.length];
for (int i = 0; i < a.length; i++) {
if((i+r) >= a.length)
A[i]=a[i+r-a.length];
else
A[i]=a[i+r];
}
return A;
Related
For some reason I have only managed as far as printing the odd numbers, but it somehow still prints what appears to be values that are null. I am trying to only print the values that returned as odd.
public class Odd {
public int[] removeEvens(int [] nums) { //start of method
int [] newArray = new int[nums.length];
int count = 0;
// start of array conversion
for(int i = 0; i < nums.length; i++) {
newArray[count] = nums[i];
count++;
}
int counter = 0;
for (int i = 0; i < nums.length; i++)
if (newArray[i] % 2 == 1)
newArray[counter++] = newArray[i];
for (int i=counter; i < nums.length; i++)
newArray[i] = 0;
return newArray;
}
// end of method
public static void main(String[] args) {
Odd labObject = new Odd();
int [] input = {1,2,3,4,5,6,7,8,9};
int [] result = labObject.removeEvens(input);
// Helper method Arrays.toString() converts int[] to a String
System.out.println(Arrays.toString(result)); // Should print [1, 3, 5, 7, 9]
}
}
change it to return Arrays.copyOfRange(newArray, 0, counter); when you make in array of ints in java with a specified size, it sets every value in the array to 0. Doing this will remove all of the extraneous 0s at the end.
This can be easily solved by working out the correct size of the new array first before you create it. Then simply loop the array and only store the odd numbers. Otherwise, remove/trim the array size before returning it.
Here is a solution by modifying your removeEvens method:
public int[] removeEvens(int[] nums)
{ //start of method
int count = 0;
// start of array conversion
// Count the odd numbers to work out the array length
for (int i = 0; i < nums.length; i++)
{
if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
{
count++;
}
}
// Now create a new array of the correct length
int[] newArray = new int[count];
// Now loop through the original array and only store the odd numbers in the new array
int counter = 0;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
{
newArray[counter] = nums[i];
counter ++;
}
}
// Return the result
return newArray;
}
Result:
[1, 3, 5, 7, 9]
I'm trying to sort an array by the number of digits in each element from largest to smallest. This technically works but it seems to sort the array by value as well. For example, instead of printing out 1234 700 234 80 52, it should print 1234 234 700 52 80 as 234 is before 700 in the original array.
public class Sort {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {52, 234, 80, 700, 1234};
int temp = 0;
//Displaying elements of original array
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in descending order
//Math function is used to find length of each element
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(Math.log10(arr[i]) + 1 < Math.log10(arr[j]) + 1) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
The easiest way to find the length of the number is to convert it into a String and then call the method length on it.
int number = 123;
String numberAsString = String.valueOf(number);
int length = numberAsString.length(); // returns 3
But you also could do it by division. The following method takes a number and divides by multiples of 10.
divide by 1 (we have at least a length of 1)
division by 10 > 0 (we have at least a length of 2)
division by 100 > 0 (we have at least a length of 3)
...
the variable i is used as dividend and the variable j is used as counter. j counts the length of the number.
As soon as number / i equals zero we return the counter value.
public int lengthOfNumber(int number) {
if (number == 0) {
return 1;
}
for (int i = 1, j = 0; ; i *= 10, j++) {
if (number / i == 0) {
return j;
}
}
}
There are multiple ways to sort the array. Here are some examples (I used the string version for comparing the values).
Use nested for-loop
public void sortArray(int[] array) {
for (int i = 0; i < array.length; i++) {
int swapIndex = -1;
int maxLength = String.valueOf(array[i]).length();
for(int j = i + 1; j < array.length; j++) {
int length2 = String.valueOf(array[j]).length();
if (maxLength < length2) {
maxLength = length2;
swapIndex = j;
}
}
if (swapIndex > -1) {
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
}
}
I used a variable swapIndex which is initialized with -1. This way we can avoid unnecessary array operations.
We take the first element in the outer for-loop and go through the rest of the array in the inner for-loop. we only save a new swapIndex if there is a number in the rest of the array with a higher length. if there is no number with a higher length, swapIndex remains -1. We do a possible swap only in the outer for-loop if necessary (if swapIndex was set).
Using Arrays.sort()
If you want to use Arrays.sort you need to convert your array from primitive type int to Integer.
public void sortArray(Integer[] array) {
Arrays.sort(array, (o1, o2) -> {
Integer length1 = String.valueOf(o1).length();
Integer length2 = String.valueOf(o2).length();
return length2.compareTo(length1);
});
}
Using a recursive method
public void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
String current = String.valueOf(array[i]);
String next = String.valueOf(array[i + 1]);
if (current.length() < next.length()) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
// here you do a recursive call
sortArray(array);
}
}
}
So I have a problem, this method is supposed to sort an array of integers by using counting sort. The problem is that the resulting array has one extra element, zero. If the original array had a zero element (or several) it's fine, but if the original array didn't have any zero elements the result starts from zero anyway.
e.g. int input[] = { 2, 1, 4 }; result -> Sorted Array : [0, 1, 2, 4]
Why would this be happening?
public class CauntingSort {
public static int max(int[] A)
{
int maxValue = A[0];
for(int i = 0; i < A.length; i++)
if(maxValue < A[i])
maxValue = A[i];
return maxValue;
}
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length + 1];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
Result[x] = A[i];
x--;
Count[A[i]] = x;
}
return Result;
}
}
You are using int[] Result = new int[A.length + 1]; which makes the array one position larger. But if you avoid it, you'll have an IndexOutOfBounds exception because you're supposed to do x-- before using x to access the array, so your code should change to something like:
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
x--;
Result[x] = A[i];
Count[A[i]] = x;
}
return Result;
}
Here you go: tio.run
int maxValue = max(A) + 1;
Returns the highest value of A + 1, so your new array with new int[maxValue] will be of size = 5;
The array Result is of the lenght A.lenght + 1, that is 4 + 1 = 5;
The first 0 is a predefinied value of int if it is a ? extends Object it would be null.
The leading 0 in your result is the initial value assigned to that element when the array is instantiated. That initial value is never modified because your loop that fills the result writes only to elements that correspond to a positive number of cumulative counts.
For example, consider sorting a one-element array. The Count for that element will be 1, so you will write the element's value at index 1 of the result array, leaving index 0 untouched.
Basically, then, this is an off-by-one error. You could fix it by changing
Result[x] = A[i];
to
Result[x - 1] = A[i];
HOWEVER, part of the problem here is that the buggy part of the routine is difficult to follow or analyze (for a human). No doubt it is comparatively efficient; nevertheless, fast, broken code is not better than slow, working code. Here's an alternative that is easier to reason about:
int nextResult = 0;
for (int i = 0; i < Count.length; i++) {
for (int j = 0; j < Count[i]; j++) {
Result[nextResult] = i;
nextResult++;
}
}
Of course, you'll also want to avoid declaring the Result array larger than array A.
I need some help inserting the number 8 into an array that gives me random values. The array must be in order. For example if I had an array of (1,5,10,15), I have to insert the number 8 between 5 and 10. I am having a problem on how I can figure our a way to find the index where 8 will be placed because the array is random, it can be anything. Here is my code so far :
public class TrickyInsert {
public static void main(String[] args) {
int[] mysteryArr = generateRandArr();
//print out starting state of mysteryArr:
System.out.print("start:\t");
for ( int a : mysteryArr ) {
System.out.print( a + ", ");
}
System.out.println();
//code starts below
// insert value '8' in the appropriate place in mysteryArr[]
int[] tmp = new int[mysteryArr.length + 1];
int b = mysteryArr.length;
for(int i = 0; i < mysteryArr.length; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
mysteryArr = tmp;
any tips? thanks!
Simply add the number then use Arrays.sort method,
int b = mysteryArr.length;
int[] tmp = new int[b + 1];
for(int i = 0; i < b; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
mysteryArr = Arrays.sort(tmp);
In your example the random array is sorted. If this is the case, just insert 8 and sort again.
Simply copy the array over, add 8, and sort again.
int[] a = generateRandArr();
int[] b = Arrays.copyOf(a, a.length + 1);
b[a.length] = 8;
Arrays.sort(b);
int findPosition(int a, int[] inputArr)
{
for(int i = 0; i < inputArr.length; ++i)
if(inputArr[i] < a)
return i;
return -1;
}
int[] tmpArr = new int[mysteryArr.length + 1];
int a = 8; // or any other number
int x = findPosition(a, mysteryArr);
if(x == -1)
int i = 0;
for(; i < mysteryArr.length; ++i)
tmpArr[i] = mysteryArr[i];
tmpArr[i] = a;
else
for(int i = 0; i < mysteryArr.length + 1; ++i)
if(i < x)
tmpArr[i] = mysteryArr[i];
else if(i == x)
tmpArr = a;
else
tmpArr[i] = mysteryArr[i - 1];
I will suggest using binary search to find the appropriate index. Once you locate the index, you can use
System.arraycopy(Object src, int srcIndex, Obj dest, int destIndex, int length)
to copy the left half to your new array (with length one more than the existing one) and then the new element and finally the right half. This will stop the need to sort the whole array every time you insert an element.
Also, the following portion does not do anything.
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
since int b = mysteryArr.length;, after setting int i =b ;, i<mysteryArr.length; will be false and hence the line inside this for loop will never execute.
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}