Reverse an Array using Java [duplicate] - java

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 7 years ago.
I filled an array with the numbers 1 to 10 using a for-loop.
Now I need to fill a second array with the values of the first array, but upside down. So the second array has to be filled with 10 to 1.
I tried something but it fills the second array with just 1.
output is:
1
2
3
4
5
6
7
8
9
10
1
1
1
1
1
1
1
1
1
1
and it should be 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1
package FillandTurn;
import java.util.Scanner;
/**
*
* #author Quinten
*/
public class FillandTurn {
/**
* #param args the command line arguments
*/
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
FillandTurn fill = new FillandTurn();
fill.start();
}
public void start(){
FillandTurn turn = FillandTurn();
int[] array = turn.vullen();
int[] array2 = turn.draaien(array);
}
public int[] fill(){
int[] array = new int[10];
int j = 0;
for(int i = 0; i < array.length; i++ ){
j++;
array[i] = j;
}
for(int p = 0; p <= array.length-1; p++ ){
System.out.println(array[p]);
}
return array;
}
public int[] turn(int[] array){
int[] array2 = new int[10];
for(int x = 0; x < array2.length; x++){
for(int y = array.length-1; y >=0; y--){
array2[x] = array[y];
}
}
for(int p = 0; p <= array2.length-1; p++ ){
System.out.println(array2[p]);
}
return array2;
}
}
Any helps is appreciated!

Have a for loop to fill the first array as stated, but then have a seperate for loop for the second array, which starts at the size of the first array, and decrements on each iteration, putting the elements into the new array

Have you tried reading the array from the back to the front?
public int[] reverseArray(int[] array1) {
int[] array2 = new int[array1.length];
int pos = 0;
for(int neg = array1.length; neg >= 0; neg--) {
array2[pos] = array1[neg];
}
return array2;
}
This is a simple way, there is probably better ways to do this.

When you copy an array you only need one loop. Using a nested loop means you are copying each value N times, or in fact the first value overwrites all the others.
You can do
class FillAndTurn {
public static void main(String... args) {
int[] array = new int[10];
fill(array);
int[] array2 = turn(array);
IntStream.of(array).forEach(System.out::println);
IntStream.of(array2).forEach(System.out::println);
}
static void fill(int[] array) {
for (int i = 0; i < array.length; i++)
array[i] = i + 1;
}
static int[] turn(int[] array) {
int[] array2 = new int[array.length];
for(int i = 0; i < array.length; i++)
array2[array2.length - i - 1] = array[i];
return array2;
}
}

Related

How to create an new one dimensional array with elements of a 2d array and return it?

I need tp create a new array with the elements of a 2d array in java. However, it only adds the last number of the 2d array which results in an array of the same value.
public class MyClass {
public static int[] collect(int[][] array) {
int[] nA = new int[10];
for (int i = 0; i < 7; i++) {
for (int[] y : array) {
for (int x : y) {
nA[i] = x;
}
}
}
return nA;
}
public static void main(String args[]){
int[][] array = {{1}, {2,3}, {4,5,6}, {7}, {}, {}, {8,9,10}};
int[] z = collect(array);
for (int x : z) {
System.out.print(x + " ");
}}
}
You have an outer loop for (int i = 0; i < 7; i++) that is causing the issues.
The value of "i" does not change and the whole array is traversed '7' times and the last element is persisted at the index specified by 'i'. And the whole thing repeats for "i+1". Ultimately what is printed is the last element of the last sub-array multiple times. That is not what you want.
Please look at the following code. Note, we also get the length of the array dynamically from the argument (never hardcode for you would like your method to be suitable for all sizes).
public static int[] collect(int[][] array) {
// calculate length
int length = 0;
for (int a[] : array) {
length += a.length;
}
int[] nA = new int[length];
// for (int i = 0; i < 7; i++) {
int i=0;
for (int[] y : array) {
for (int x : y) {
nA[i++] = x;
}
}
// }
return nA;
}
public static void main(String args[]) {
int[][] array = {{1}, {2, 3}, {4, 5, 6}, {7}, {}, {}, {8, 9, 10}, {11}};
int[] z = collect(array);
for (int x : z) {
System.out.print(x + " ");
}
}
Prints:
1 2 3 4 5 6 7 8 9 10 11
public class MyClass {
public static int[] collect(int[][] array) {
int[] nA = new int[10];
int k=0;
for (int i = 0; i < array.length; i++) {
for (int j=0; j< array[i].length;j++) {
nA[k] = array[i][j];
k++;
}
}
return nA;
}
public static void main(String args[]){
int[][] array = {{1}, {2,3}, {4,5,6}, {7}, {}, {}, {8,9,10}};
int[] z = collect(array);
for (int x : z) {
System.out.print(x + " ");
}}
}
Change your code as above. However to work this solution you have know the size of new array beforehand. No need of 3 for loops. Variable k use to identify the new array current index.
You only need two for loops to go through a 2D Array.
Furthermore it is not a good idea to hard code the length of the array you return. If you don't want to use any other data structures in addition, I think you have no other chance for calculating the length of the new array than iterating over the whole 2D array to calculate the number of elements, initialize the new one with that size and than iterating again over the 2D array to fill the new one.
In code:
public static int[] collect(int[][] array) {
int numberOfElements = 0;
for(int i = 0; i < array.length; i++)
numberOfElements += array[i].length;
int[] nA = new int[numberOfElements];
int fillingCounter = 0;
for (int i = 0; i < array.length; i++) {
int[] current = array[i];
for (int j = 0; j < current.length; j++) {
nA[fillingCounter] = array[i][j];
fillingCounter++;
}
}
return nA;
}
Alternatively, you can use a dynamic data structure (for example java.util.LinkedList) and then convert it to an array (for example with the toArray method)

How to find largest 10 elements in multi dimentional array?

I hope this will print one largest value. but it need 10 largest elements in an 3D array.
public class foo{
Public static void main(String[] args){
int row,col,dep=3;
int[][][] value=new int[row][col][dep];
/* insert the value from user or initialize the matrix*/
int max=0;
for(row=0;row<3;row++)
for(col=0;col<3;col++)
for(dep=0;dep<3;dep++)
if(value[row][col][dep]>max)
max=value[row][col][dep];
System.out.println(max);
}
}
You can add all integers into a List<Integer>, sort it, and then get the X max numbers of it:
public class foo {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
List<Integer> listWithAll = new ArrayList<>();
/* insert the value from user or initialize the matrix*/
int max = 0;
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
for (dep = 0; dep < 3; dep++)
listWithAll.add(value[row][col][dep]);
listWithAll.sort(Collections.reverseOrder());
for (int i = 0; i < 10; i++) {
System.out.println(listWithAll.get(i));
}
}
}
which prints:
15 10 0 0 0 0 0 0 0 0
or using Java 8 streams only:
List<Integer> max10 = listWithAll.stream()
.sorted(Collections.reverseOrder())
.limit(10)
.collect(Collectors.toList());
max10.forEach(System.out::println);
Here is a way to do it with streams. I used a complete 2 x 2 x 2 array to make it easier but it would work with any int[][][] array. Instead of using nested loops, I just flatMapped the arrays.
Initialize the array.
int[][][] v = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
Now get the top4 values (or top N values) and put them in a list.
int top4 = 4;
List<Integer> top4Max =
Arrays.stream(v).flatMap(Arrays::stream).flatMapToInt(
Arrays::stream).boxed().sorted(
Comparator.reverseOrder()).limit(top4).collect(
Collectors.toList());
System.out.println(top4Max);
Prints
8 7 6 5
The Arrays.stream strips one level of array. The flatMap takes those and further flattens them into a single dimenion array. The flatMapToInt flattens that into a stream of ints where they are sorted and processed into a limited collection.
If required, you could also put them in an array instead of a list.
Alternatively, one could create a small array and use it as with a normal findmax function.
public class Array_3D {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
int[] topten = new int[10]; //array to hold max values
int count = 0;
int candidate = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < dep; k++) {
if (count < 10) { //start with first ten values
topten[count] = value[i][j][k];
count++;
}
else {
candidate = value[i][j][k];
for (int x = 0; x < 10; x++) { //loop for loading top values
if (candidate > topten[x]) {
topten[x] = candidate;
break; //exit on first hit
}
}
}
}
}
}
for (int i = 0; i < 10; i++) {
System.out.print(topten[i] + " ");
}
System.out.println();
}
}
I don't know which method is faster for large 3D arrays; here we have to run a small loop at every point in the 3D array, vs creating an entirely new list and sorting it. Clearly this wins in memory usage, but not sure about speed. [Edit note this returns an unsorted array of the top ten values as is].

Create a reverse order array from given array

I have an assignment to create a class in which I create an array of size 10, called source, and assign random integers in the range 0-10 to all indexes in it, and then call a method that creates a new array in reverse order. I tried the code below:
public class Exercise7_4 {
// reverse array method
public static int[] reverseArray(int[] arr) {
int[] reverse = new int[arr.length];
for (int i = 0; i < reverse.length - 1; i++) {
reverse[i] = arr[arr.length - 1 - i];
}
return reverse;
}
// print array in ascending order
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
System.out.printf("%d\t", arr[i]);
}
System.out.println();
}
public static void main(String[] args) {
int[] source = new int[10];
for (int i = 0; i < source.length - 1; i++) {
source[i] = (int) (Math.random() * 10 + 1);
}
int[] reverse = reverseArray(source);
printArray(source);
printArray(reverse);
}
}
The problem is that the output i get looks like this:
7 1 3 7 10 9 6 2 6
0 6 2 6 9 10 7 3 1
meaning, the reverseArray method doesn't work properly on reverse[0] for some reason.
I would like to know why this is happening and how I can fix it.
Thanks in Advance!
change all your for-loops from
for (int i = 0; i < source.length - 1; i++)
to
for (int i = 0; i < source.length; i++)
Your reverse method is completely correct (if you change the loop). The mistake you made is that you created an array of size 10, filled it with 9 random values (the value of index 10 will therefore be 0).
You could check wich index are consulted in each iteration of your for loop.
This is your solution
for (int i = 0; i < reverse.length - 1; i++) {
System.out.println("" + i + " " + (reverse.length - 1 - i));
}
And it prints:
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
The 'i' don't get the value 9, and the (reverse.length - 1 - i) don't get the value 0.
Changing the testing condition for this:
i < reverse.length
gives you the last position:
9 0
Change reverseArray function as follows:
public static int[] reverseArray(int[] arr) {
int[] reverse = new int[arr.length];
for (int i = 0; i < reverse.length; i++) {
reverse[i] = arr[arr.length - i];
}
return reverse;
}
You need not to -1 from arr.length.
Change another for loop also:
for (int i = 0; i < source.length; i++) {
source[i] = (int) (Math.random() * 10 + 1);
}
Here, also you do not need to do -1 from source.length.
package com.test;
public class SortArray {
private int[] getSortedArry(int[] arr){
int arrLen = arr.length;
int reversedArry[] = new int[arrLen];
System.out.println("array lenght: " +arr.length);
int j = 0;
for(int i=arrLen-1; i>=0; i--){
reversedArry[j] = arr[i];
j++;
}
System.out.print("\n");
return reversedArry;
}
public static void main(String[] args){
int arr[] = {10,2,3,4,5,12,23,43,45,65};
SortArray sortArray = new SortArray();
int reversedArry[] = sortArray.getSortedArry(arr);
for(int i=0;i<reversedArry.length;i++){
System.out.print(reversedArry[i] + " ");
}
}
}

Array method that returns a new array where every number is replicated by “itself” # of times

I am trying to write a method in Java that receives an array and returns a new array where each number is printed that number of times. Here is an example input and output: "1 2 3 0 4 3" ---> "1 2 2 3 3 3 4 4 4 4 3 3 3". I am stuck and my program will not compile. Does anyone see where I am going wrong?
public static int [] multiplicity(int [] nums) {
for (int i = 0 ; i < nums.length ; i++) {
int size = nums.length + 1;
int newNums[] = new int [size];
for (int j = 0 ; j < nums.length ; j++) {
int value = nums[j];
for (int v = 0 ; v < value ; v++) {
newNums[j + v] = value;
}
}
}
return newNums;
}
Your current code does not size your new array correctly, you could fix your compiler errors easily enough like
int size=nums.length+1;
int newNums [] = new int [size];
for (int i=0; i<nums.length; i++)
{
// int size=nums.length+1;
// int newNums [] = new int [size];
But that clearly won't allow you to populate all of your values. Instead (assuming you can't use a dynamic data-type like a Collection), you'll need to iterate the array once to get the final count of elements and then populate your array. Something like,
public static int[] multiplicity(int[] nums) {
// first pass
int count = 0;
for (int num : nums) {
for (int i = 0; i < num; i++) {
count++;
}
}
int[] ret = new int[count];
count = 0;
// second pass
for (int num : nums) {
for (int i = 0; i < num; i++) {
ret[count++] = num;
}
}
return ret;
}
Then you could test it like,
public static void main(String arg[]) {
int[] in = { 1, 2, 3, 0, 4, 3 };
int[] out = multiplicity(in);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < out.length; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append(out[i]);
}
String expected = "1 2 2 3 3 3 4 4 4 4 3 3 3";
System.out.println(expected.equals(sb.toString()));
}
Output is
true
Once you initialise your int[] newNums, you can't dynamically resize it. Initialising it again will discard the previous array.
Here's another way to solve the problem:
public static int [] multiplicity (int [ ] nums)
{
// create a list to contain the output
List<Integer> newNums = new ArrayList<Integer>();
// for each incoming int
if(nums != null) {
for (final int i : nums)
{
// repeat adding the value
for(int j = 0; j < i; j++) {
newNums.add(i);
}
}
}
// now copy from the List<Integer> to the result int[]
int[] result = new int[newNums.size()];
for(int i=0; i < newNums.size(); i++) {
result[i] = newNums.get(i);
}
// return the result
return result;
}
You can't know the new array size until you explore the whole input array.
So you can
Explore the whole array and compute the lengh, then, re-explore the input array and fill the new. You need only 1 memory allocation (only 1 new int[])
Create a vector and fill it. Then use the .toarray method
Exemple to fill the array (check he had the right size)
int k = 0
for(int i: nums) {
for(int j = 0; j < i; j++) {
newArray[k] = i;
k++;
}
}

Swapping two 2D Arrays of integers

I am looking to completely swap the contents of two arrays, not swap integers within the array, but across the two. I am just very confused as to where to begin.
ie...
Matrix a = 1 2 3 Matrix b = 3 2 1
4 5 6 6 5 4
I wish for it to output as
Matrix a = 3 2 1 Matrix b = 1 2 3
6 5 4 4 5 6
If that makes sense. Sorry! My code is below for the beginning part of creating the array and filling it with Random, I didn't include the tester because I'm simply inputting which array to use for the calculation, and I am not ready to do that yet.
import java.util.Random;
public class Matrix {
private int[][] matrix;
private int rows;
//constructors
public Matrix() {
matrix = new int[3][3];
rows = 3;
}
public Matrix(int size) {
matrix = new int[size][size];
rows = size;
}
//Mutators
public void fill() {
Random r = new Random();
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.rows; j++) {
this.matrix[i][j] = r.nextInt();
}
}
}
public void clear() {
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.rows; j++) {
this.matrix[i][j] = 0;
}
}
}
public static void swap(Matrix a, Matrix B) {
}
}
You can simply swap the matrix fields:
public static void swap(Matrix a, Matrix b) {
int[][] tmp = a.matrix;
a.matrix = b.matrix;
b.matrix = tmp;
}
You should probably first check that the matrices have the same size. Alternatively, also swap the value of the rows field between a and b.

Categories