I'm having difficulty with the action below. I'm not sure how to reverse the array index starting at n and working down to 0. Can someone help me understand this? I'm thinking of using a for loop, but I can't quite visualize how I would do that.
Thanks.
• Add a method called public static int[] generateIntegerArray(int n) to the App class that returns a systematically generated integer array of length n that is reverse sorted starting at n-1 and ending at 0. For example a call generateIntegerArray(5) would result in this array: {4, 3, 2, 1, 0}.
public static int[] generateIntegerArray(int n){
int[] integerArray = new int[n];
return integerArray;
}
Try something like this:
int[] integerArray = new int[n];
for(int i = 0; i < n; i++) {
integerArray[i] = n - i - 1;
}
return integerArray;
}
You should just fill that array with values from n-1 to 0
for(int i=0; i<n; i++) {
integerArray[i] = n-i-1;
}
or
for(int i=n; i>0; i--) {
integerArray[n-i-1] = i;
}
public static int[] generateIntegerArray(int n){
int[] integerArray = new int[n];
for(int i = n - 1; i >= 0; --i){
integerArray[n - 1 - i] = i;
}
return integerArray;
}
The for loop would run from n - 1 to 0 and the values would be put into array
for (int i = integerArray.length-1 ; i >=0; i--)
{
integerArray[i] = i;
}
That looks like(if lenght is 6, for example):
6,5,4,3,2,1,0
i - is number in loop, it changes in every loop(i--);
So, at the output it will looks like:
integerArray[6]
integerArray[5]
integerArray[4]
integerArray[3]
integerArray[2]
integerArray[1]
integerArray[0]
If I understood you in right way)
int[] integerArray = new int[]{1,2,3,4,5,6,7,8,9};
int[] reversedArray = new int[integerArray.length];
int j = 0;
for (int i = integerArray.length -1; i > 0; i--){
reversedArray[j++] = integerArray[i];
}
Hope you find this helpful..
public static int[] generateIntegerArray(int n){
int[] integerArray = new int[n];
for(int i = 0; i < n; i++) {
integerArray[i] = n - i - 1;
}
return integerArray;
}
Related
supposed to return true if the first half of an array is equal to the second but it keeps return false... I tried debugging but still doesn't work... Help!
public class Main {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 1, 2, 3};
System.out.println(sda(arr));
}//main
public static boolean sda(int[] arr) {
int[] arr2 = new int[arr.length];
int[] arr3 = new int[arr.length];
for(int i = 0; i < (arr2.length/2); i++) {
arr2[i] = arr[i];
}
for(int i = arr.length - 1; i > (arr.length/2) - 1; i--) {
arr3[i] = arr[i];
}
for(int j = 0; j < arr.length/2 - 1; j++) {
if(arr3[j] != arr2[j]) return false;
}
return true;
}
}
any suggestions?
Emmm... Well, a good resolve method is to debug on the value of arr2 and arr3. Then you'll find this:
int arr2[] = {1, 2, 3, 0, 0, 0};
int arr3[] = {0, 0, 0, 1, 2, 3};
Come on! Do it and resolve it.
If I break down the current code:
First arr2 and arr3 are assigned an empty array of 6 items.
Next arr2 is assigned values (1,2,3) in the first 3 elements of the array.
Then arr3 is assigned (1,2,3) in the final 3 elements of the array.
If I add the below code snipper under the 2nd for-loop:
System.out.println("arr2: ");
for(int i : arr2){
System.out.println(i);
}
System.out.println("arr3: ");
for(int i : arr3){
System.out.println(i);
}
You will see that that the two arays are different.
arr2:
1
2
3
0
0
0
arr3:
0
0
0
1
2
3
To make the result return true, you could adjust where the arr2 values are placed or adjust where the arr3 values are placed within the array.
An alternative solution would be to change the evaluation of the two array values in the final for-loop to be:
for(int j = 0; j < arr.length/2 - 1; j++) {
if(arr3[j + (arr.length/2)] != arr2[j]) return false;
}
This way the evaluation of the two loops will be for the first 3 values of arr2 against the final 3 values of arr3.
In summary, I have changed the sda method to below:
public static boolean sda(int[] arr) {
int[] arr2 = new int[arr.length];
int[] arr3 = new int[arr.length];
for(int i = 0; i < (arr2.length/2); i++) {
arr2[i] = arr[i];
}
for(int i = arr.length - 1; i > (arr.length/2) - 1; i--) {
arr3[i] = arr[i];
}
for(int j = 0; j < arr.length/2 - 1; j++) {
if(arr3[j + (arr.length/2)] != arr2[j]) return false;
}
return true;
}
public static boolean sda(int[] arr) {
for(int i=0, j=arr.length/2; i<arr.length/2 || j<arr.length; i++, j++)
if(arr[i]!=arr[j])
return false;
return true;
}
I would like to join two arrays but not like the usual way
{1,2,3} {4,5,6}
{1,2,3,4,5,6}
I would like to join them like so
{1,2,3} {4,5,6}
{1,4,2,5,3,6}
any suggestions?
I do not want to concatenate the two arrays but rather zip them
This Program also work for if array size of both is not equals.. Happy to help
public class Assignment{
public static void main(String[] args){
int [] arr1 = new int[]{1,2,3};
int [] arr2 = new int[]{4,5,6,7,8};
int [] arr3 = new int[arr1.length + arr2.length];
int biglength = 0;
if(arr1.length > arr2.length){
biglength = arr1.length;
}else{
biglength = arr2.length;
}
for(int i=0,j=0; i< biglength; i++){
if(i<arr1.length && i<arr2.length){
arr3[j++] = arr1[i];
arr3[j++] = arr2[i];
}else if(i<arr1.length){
arr3[j++] = arr1[i];
}else{
arr3[j++] = arr2[i];
}
}
for(int j= 0 ; j<arr3.length; j++){
System.out.print(arr3[j]);
}
}
}
Here is a technique using Java 8 streams:
int[] mergedArray = IntStream.range(0, Math.min(array1.length, array2.length))
.flatMap(n -> IntStream.of(array1[n], array2[n]))
.toArray();
VerA - on List and Integer, returned Integer[];
VerB - on array and int, returned int[];
Mixes n arrays where the length can be different.
public static Integer[] arraysMixVerA(Integer[]... arrays) {
List<Integer> list = new ArrayList<>();
int max=-1;
for (Integer[] array : arrays) {
max = Math.max(max, array.length);
}
for (int i = 0; i < max*arrays.length; i++) {
list.add(null);
}
for (int i = 0; i < arrays.length; i++) {
for (int j = 0; j < arrays[i].length; j++) {
list.set(j * arrays.length + i, arrays[i][j]);
}
}
for(int i=0;i<list.size();i++){
if(list.get(i)==null)
list.remove(i);
}
return list.toArray(new Integer[list.size()]);
}
public static int[] arraysMixVerB(int[]... arrays) {
int max=-1;
int sumaIndex=0;
for (int[] array : arrays) {
max = Math.max(max, array.length);
sumaIndex=sumaIndex+array.length;
}
Integer[] temp=new Integer[max*arrays.length]; //For an array of
//type int, the default value is 0. For an array of type Integer,
//the default value is null. Thus could not be distinguish zeros with arrays
//that are arguments methods of zeros from the array "temp".
int[] target=new int[sumaIndex];
for (int i = 0; i < arrays.length; i++) {
for (int j = 0; j < arrays[i].length; j++) {
temp[j * arrays.length + i]=arrays[i][j];
}
}
for(int i=0,j=0;i<temp.length;i++){
if(temp[i]!=null){
target[j++]=temp[i];
}
}
return target;
}
O(m) + O(n) is the maximum you can achieve here and accurate answered have already been provided here.
However if array size is extremity higher let's say 10^7 and if you'd want to reduce computation time little more by imposing on your machine cores and comfortable with slight complication in the code you can use concurrency here.
int[] arr1 = new int[10000010];
int[] arr2 = new int[10000000];
int end, endFinal;
int[] output = new int[arr1.length+arr2.length];
if( arr1.length < arr2.length )
end = arr1.length;
else
end = arr2.length;
endFinal = arr1.length + arr2.length;
T obj1 = new T( arr1, output, 0, end );
T obj2 = new T( arr2, output, 1, end );
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start();
t2.start();
t1.join();
t2.join();
for( int j = 2*end; j<endFinal; j++)
{
if(endFinal == arr1.length)
output[j] = arr1[end++];
else
output[j] = arr1[end++];
}
}
class T implements Runnable {
int[] arr, output;
int start, end;
public T ( int[] arr, int[] output, int start, int end)
{
this.arr = arr;
this.output = output;
this.start = start;
this.end = end;
}
public void run (){
int count = 0;
for (int i = start; i< end; i+=2)
output= arr[count++];
}
}
So both the threads will populate m number of elements assuming m is less than n and rest n - m forms will be populated normally. This may seem like a complicated solution and should only be used if necessary. One may not see the difference in smaller arrays.
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;
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;
}
CodingBat > Java > Array-1 > reverse3:
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
public int[] reverse3(int[] nums) {
int[] values = new int[3];
for (int i = 0; i <= nums.length - 1; i++) {
for (int j = nums.length-1; j >= 0; j--) {
values[i] = nums[j];
}
}
return values;
}
I can't get this to work properly, usually the last int in the array, becomes every single int in the new array
You don't want a two-level loop. Just have one loop:
for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
values[i] = nums[j];
}
or, alternately, just don't track j sepearately, and do this:
for(int i = 0; i < nums.length; i++) {
values[i] = nums[nums.length - 1 - i];
}
Unless this is a homework, why not just use Apache ArrayUtils'
ArrayUtils.reverse(nums)
Never re-invent the wheel :)
The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.
public int[] reverse3(int[] nums) {
return new int[] { nums[2], nums[1], nums[0] };
}
See also:
CodingBat/Java/Array-1/reverse3
Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.
Firstly, while creating new array give it size of old array.
Next, when you're reversing an array, you don't need two loops, just one:
int length = oldArray.length
for(int i = 0; i < length; i++)
{
newArray[length-i-1] = oldArray[i]
}
You only want a single loop, but with indices going both ways:
public int[] reverse(int[] nums) {
int[] back = new int[nums.length];
int i,j;
for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
back[i] = nums[j];
return back;
}
public int[] reverse3(int[] nums) {
int rotate[]={nums[2],nums[1],nums[0]};
return rotate;
}
This code gives correct output:-
public int[] reverse3(int[] nums) {
int[] myArray=new int[3];
myArray[0]=nums[2];
myArray[1]=nums[1];
myArray[2]=nums[0];
return myArray;
}
I got this with Python.. So you can get the idea behind it
def reverse3(nums):
num = []
for i in range(len(nums)):
num.append(nums[len(nums) - i - 1])
return num
In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations.
First of all, very bad logic to have two loops for a simple swap algorithm such as :
public static void reverse(int[] b) {
int left = 0; // index of leftmost element
int right = b.length-1; // index of rightmost element
while (left < right) {
// exchange the left and right elements
int temp = b[left];
b[left] = b[right];
b[right] = temp;
// move the bounds toward the center
left++;
right--;
}
}//endmethod reverse
or simplified:
for (int left=0, int right=b.length-1; left<right; left++, right--) {
// exchange the first and last
int temp = b[left]; b[left] = b[right]; b[right] = temp;
}
Why go through all this pain, why dont you trust Java's built-in APIs and do something like
public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}
public int[] reverse3(int[] nums) {
int[] values = new int[nums.length];
for(int i=0; i<nums.length; i++) {
values[nums.length - (i + 1)]=nums[i];
}
return values;
}