How to pass by value in java? [duplicate] - java

This question already has answers here:
Problem with assigning an array to other array in Java
(4 answers)
Make copy of an array
(11 answers)
Closed 2 years ago.
I'm trying to make a project in which an array is sorted by different sorting algorithms. However, I have noticed that after one algorithm sorts the array and displays the value, the original array is also changed. How can I solve this?
public static void main(String[] args) {
int[] array = {20, 35, -15, 7, 55, 1, -2};
printArray(array);
boubleSort(array);
printArray(array);
}
The first function prints out the array in its unsorted form, the second one sorts the array and then prints the sorted array. The third line prints the original array (which should remain unsorted) as sorted. Why odes this occur and how can I change this?
public static void boubleSort(int[] array) {
System.out.println("Bouble Sort");
int [] arr = array;
for(int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
for (int i = 0; i < lastUnsortedIndex;i++) {
if(arr[i] < arr[i+1]) {
swap(arr,i, i+1);
}
}
}
printArray(arr);
}
public static void swap(int [] array, int i, int j) {
if (i == j) {
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void printArray(int [] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println();
}
Current output: Desired output:
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2
Bouble Sort
35 35
20 20
7 7
1 1
-2 -2
-15 -15
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2

Related

an int array from Command Line Arguments

I'm trying to convert command line arguments in an int array, but it appears a "0" in the end of the array. How can I fix it?
import java.util.Arrays;
public static void main(String[] args){
int[] game = new int[9];
for (int i = 0; i <= 8; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
Example run:
$ java edu.kit.informatik.TicTacToe 5 6 4 1 2 3 7 8 9
[5, 6, 4, 1, 2, 3, 7, 8, 9, 0]
I have tested your code, there aren't '0' at the end of the list. I recommend you that use args.length for handling variety arguments count.
public static void main(String[] args) {
int[] game = new int[args.length];
for (int i = 0; i < args.length; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
When you create a new int[] array in Java, its initial contents are all zeros. If you then fill it up with fewer numbers than it is long, you'll see the zeros that have not been overwritten at the end.
// creating an array of size 10
int[] array = new int[10];
// only filling up the first 8 elements
for (int i = 1; i <= 8; i++) {
array[i-1] = i;
}
// printing the full array
for (int i = 0; i < array.length; i++) {
System.out.print(i + " ");
}
System.out.println();
This will output:
1 2 3 4 5 6 7 8 0 0
The last two zeros are just the elements that have not been set to anything else.

How to initialize values in a local array? [duplicate]

This question already has answers here:
How to initialize an array in Java?
(11 answers)
Closed 5 years ago.
I'm running into a little trouble understanding how I can initialize an array with the values that are listed in the notes. How would I be able to set up array and proceed to use the code below to properly return the respective output.
This question varies from the duplicate linked because it is asking how to initialize the array within a local method.
/*Write a method that reverses the sequence of elements in an array. For example, if
you call the method with the array
1 4 9 16 9 7 4 9 11
then the array is changed to
11 9 4 7 9 16 9 4 1*/
public static void reverse(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
First you need to define an array and to initialize it with the given values. This could be done directly on the declaration of the variable. Then you need to pass the reference to the reverse method.
public static void main(String[] args) {
int[] array = {1, 4, 9, 16, 9, 7, 4, 9, 11};
reverse(array);
Arrays
.stream(array)
.forEach(System.out::println);
}
private static void reverse(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
You can find more information about how to initialize an array here:
http://www.baeldung.com/java-initialize-array

Cut and Stack the Array

I have an array of int as input. The array will always be a length of 2^n. I want to cut the array in half and stack it. Repeat cutting and stacking until there is only one stack. For example:
int[] array = {1,2,3,4,5,6,7,8}
if we cut the array in half we and stack them it would be:
{1,2,| 3,4}
{5,6,| 7,8}
cut it and stack again:
{1,|2}
{5,|6}
{3,|4}
{7,|8}
again:
{1}
{5}
{3}
{7}
{2}
{6}
{4}
{8}
the desired output would be an array of int from the top to the end of the stack
int[] output = {1,5,3,7,2,6,4,8}
I have tried to construct the output array by looping the input array in a particular way. Note that when I reach the array I just start from the head again. I start at the array[i] where i = 0. I get the first number this way. then I increment i by n where n is the log(array.legnth) (base 2). This is how I get the second number. For the third number, we increment i by (n + n/2). For the fourth number, we increment i by n again. I am wondering is there a pattern? Or what would be your approach to solve this problem? I am looking for a solution in java or python.
Edit/Update:
I tried a new approach using queue. I basically keep cutting array in half and push both half of array into queue until arrays in queue all have length of 2 (or the stack is at height n). but my result is not correct. I think it has to do with the order I add the half arrays back into the queue.
import java.util.*;
public class StackArray{
public static void main(String[] args){
int[] array = {1,2,3,4,5,6,7,8};
int[] answer = stackArray(array);
for(int n : answer){
System.out.println(n);
}
}
public static int[] stackArray(int[] array){
int height = (int) (Math.log(array.length)/Math.log(2)) + 1;
Queue<int[]> queue = new LinkedList<int[]>();
ArrayList<Integer> list = new ArrayList<>();
queue.add(array);
while(queue.size() < height){
int currentLength = queue.size();
int i = 0;
while(i < currentLength){
int[] temp = queue.poll();
int[] array1 = new int[temp.length/2];
int[] array2 = new int[temp.length/2];
System.arraycopy(temp, 0, array1, 0, array1.length);
System.arraycopy(temp, array1.length, array2, 0, array2.length);
queue.add(array1); //I think the problem is here
queue.add(array2);
i++;
}
}
int y = 0;
while(y < 2){
for(int i = 0; i < queue.size(); i++){
int[] curr = queue.poll();
list.add(curr[y]);
queue.add(curr);
}
y++;
}
int[] ret = new int[list.size()];
for(int i = 0; i < list.size(); i++){
ret[i] =list.get(i);
}
return ret;
}
}
result:
1
3
5
7
2
4
6
8
how would I fix this?
update: I solved it and posted my own answer. but I am still curious as of how would other people solve this. Please stil feel free to answer.
I think the pattern becomes clear if you use 0-based indices
and express numbers in binary. e.g
0 1 2 3 4 5 6 7
000 001 010 011 100 101 110 111
0 1 2 3
000 001 010 011
100 101 110 111
4 5 6 7
0 = 000 001 = 1
4 = 100 101 = 5
2 = 010 011 = 3
6 = 110 111 = 7
0 = 000
4 = 100
2 = 010
6 = 110
1 = 001
5 = 101
3 = 011
7 = 111
see the pattern in the left-most bits? the sequence is just
the numbers 0,1,2 .. with the bit order reversed.
I solved it using two artillery queues and a main queue:
import java.util.*;
public class StackArray{
public static void main(String[] args){
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int[] answer = stackArray(array);
for(int n : answer){
System.out.println(n);
}
}
public static int[] stackArray(int[] array){
int height = (int) (Math.log(array.length)/Math.log(2)) + 1;
Queue<int[]> queue = new LinkedList<int[]>();
ArrayList<Integer> list = new ArrayList<>();
Queue<int[]> queue1 = new LinkedList<int[]>();
Queue<int[]> queue2 = new LinkedList<int[]>();
queue.add(array);
while(queue.size() < height){
int currentLength = queue.size();
int i = 0;
while(!queue.isEmpty()){
int[] temp = queue.poll();
int[] array1 = new int[temp.length/2];
int[] array2 = new int[temp.length/2];
System.arraycopy(temp, 0, array1, 0, array1.length);
System.arraycopy(temp, array1.length, array2, 0, array2.length);
queue1.add(array1); //I think the problem is here
queue2.add(array2);
i++;
}
while(!queue1.isEmpty()){
int[] temp1 = queue1.poll();
queue.add(temp1);
}
while(!queue2.isEmpty()){
int[] temp2 = queue2.poll();
queue.add(temp2);
}
}
int y = 0;
while(y < 2){
for(int i = 0; i < queue.size(); i++){
int[] curr = queue.poll();
list.add(curr[y]);
queue.add(curr);
}
y++;
}
int[] ret = new int[list.size()];
for(int i = 0; i < list.size(); i++){
ret[i] =list.get(i);
}
return ret;
}
}
output;
1
5
3
7
2
6
4
8
also test on when n = 4:
1
9
5
13
3
11
7
15
2
10
6
14
4
12
8
16

Recursive function that reverses subarray X[i,...,j]. Elements from index i to j inclusive

So I am working on a textbook practice problem focusing on recursion which I'm half way there. I have come up with two functions that recursive copy the element in one array into another, but I am sort of stuck on my reverseArray3 function.
reverseArray3 should reverse the subarray X[i,...j] consisting of those elements from index i to index j inclusive. I know it should do this by swapping elements at position i and j then calling itself recursively on subarray X[i+1,...,j-1] from index i+1 and j-1.
I tried to look up question similar to mine, but no luck. Any help
class Recursion {
static void reverseArray1(int[] X, int n, int[] Y) {
if(n < 1)
return;
Y[Y.length-n] = X[n-1];
reverseArray1(X, n-1, Y);
}
static void reverseArray2(int[] X, int n, int[] Y) {
if(n < 1)
return;
Y[n-1] = X[X.length-n];
reverseArray2(X, n-1, Y);
}
static void reverseArray3(int[] X, int i, int j) {
//Where I'm stuck
}
public static void main(String[] args) {
int[] A = {-1, 2, 3, 12, 9, 2, -5, -2, 8, 5, 7};
int[] B = new int[A.length];
int[] C = new int[A.length];
for(int x: A) System.out.print(x+" ");
System.out.println();
reverseArray1(A, A.length, B);
for(int x: B) System.out.print(x+" ");
System.out.println();
reverseArray2(A, A.length, C);
for(int x: C) System.out.print(x+" ");
System.out.println();
reverseArray3(A, 0, A.length-1);
for(int x: A) System.out.println(x+" ");
System.out.println();
}
}
below is how the output should look like:
1 2 6 12 9 2 -5 -2 8 5 7
7 5 8 -2 -5 2 9 12 6 2 -1
7 5 8 -2 -5 2 9 12 6 2 -1
7 5 8 -2 -5 2 9 12 6 2 -1
I suggest this:
static void reverseArray3(int[] X, int i, int j) {
if(i>=j)
return;
int a=X[j];
X[j]=X[i];
X[i]=a;
reverseArray3(X,i+1,j-1);
}
I hope it helps.

How to print Two-Dimensional Array like table

I'm having a problem with two dimensional array. I'm having a display like this:
1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc
What basically I want is to display to display it as:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 ... etc
Here is my code:
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;}
}
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
System.out.print("");}
}
If you don't mind the commas and the brackets you can simply use:
System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
Output
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.
You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".
You could write a method to print a 2d array like this:
//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
A part from #djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.
Do this way:-
int twoDm[][]= new int[5][7];
for(i=0;i<5;i++){
for(j=0;j<7;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println("");
}
I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.
From the initial question, as has been adequately explained by #djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:
System.out.println();
However, printing that immediately after the first print statement gives erroneous results. What gives?
1
2
...
n
This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!
Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println();
}
And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.
Just for the records, Java 8 provides a better alternative.
int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};
System.out.println(Stream.of(table)
.map(rowParts -> Stream.of(rowParts
.map(element -> ((Integer)element).toString())
.collect(Collectors.joining("\t")))
.collect(Collectors.joining("\n")));
More efficient and easy way to print the 2D array in a formatted way:
Try this:
public static void print(int[][] puzzle) {
for (int[] row : puzzle) {
for (int elem : row) {
System.out.printf("%4d", elem);
}
System.out.println();
}
System.out.println();
}
Sample Output:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
You can creat a method that prints the matrix as a table :
Note: That does not work well on matrices with numbers with many digits and
non-square matrices.
public static void printMatrix(int size,int row,int[][] matrix){
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
for(int i = 1;i <= matrix[row].length;i++){
System.out.printf("| %4d ",matrix[row][i - 1]);
}
System.out.println("|");
if(row == size - 1){
// when we reach the last row,
// print bottom line "---------"
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
}
}
public static void main(String[] args){
int[][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
// print the elements of each row:
int rowsLength = matrix.length;
for(int k = 0; k < rowsLength; k++){
printMatrix(rowsLength,k,matrix);
}
}
Output :
---------------------
| 1 | 2 | 3 | 4 |
---------------------
| 5 | 6 | 7 | 8 |
---------------------
| 9 | 10 | 11 | 12 |
---------------------
| 13 | 14 | 15 | 16 |
---------------------
I created this method while practicing loops and arrays, I'd rather use:
System.out.println(Arrays.deepToString(matrix).replace("], ", "]\n")));
Iliya,
Sorry for that.
you code is work. but its had some problem with Array row and columns
here i correct your code this work correctly, you can try this ..
public static void printMatrix(int size, int row, int[][] matrix) {
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
for (int i = 1; i <= matrix[row].length; i++) {
System.out.printf("| %4d ", matrix[row][i - 1]);
}
System.out.println("|");
if (row == size - 1) {
// when we reach the last row,
// print bottom line "---------"
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
}
}
public static void length(int[][] matrix) {
int rowsLength = matrix.length;
for (int k = 0; k < rowsLength; k++) {
printMatrix(rowsLength, k, matrix);
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }
};
length(matrix);
}
and out put look like
----------------------
| 1 | 2 | 5 |
----------------------
| 3 | 4 | 6 |
----------------------
| 7 | 8 | 9 |
----------------------
Declared a 7 by 5 array which is similar to yours, with some dummy data. Below should do.
int[][] array = {{21, 12, 32, 14, 52}, {43, 43, 55, 66, 72}, {57, 64, 52, 57, 88},{52, 33, 54, 37, 82},{55, 62, 35, 17, 28},{55, 66, 58, 72, 28}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // the trick is here, print a new line after iterating first row.
}
public class class1 {
public static void main(String[] args){
int[][] a={{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i< a.length; i++){
System.out.print("Row" + (i + 1) + ": ");
for (int j = 0; j < a[i].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
result:
Row1: 1 2 3
Row2: 4 5 6
This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.
public static void display(int x[][]) // So we allow the method to take as input Multidimensional arrays
{
//Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
for(int rreshti = 0; rreshti < x.length; rreshti++) // Loop for the rows
{
for(int kolona = 0; kolona < x[rreshti].length;kolona++) // Loop for the columns
{
System.out.print(x[rreshti][kolona] + "\t"); // the \t simply spaces out the elements for a clear view
}
System.out.println(); // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look
}
}
After you complete creating this method, you simply put this into your main method:
display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)
NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)
Source: enter link description here
PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.
For traversing through a 2D array, I think the following for loop can be used.
for(int a[]: twoDm)
{
System.out.println(Arrays.toString(a));
}
if you don't want the commas you can string replace
if you want this to be performant you should loop through a[] and then print it.
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 5 },
{ 3, 4, 6 },
{ 7, 8, 9 }
};
System.out.println(" ** Matrix ** ");
for (int rows = 0; rows < 3; rows++) {
System.out.println("\n");
for (int columns = 0; columns < matrix[rows].length; columns++) {
System.out.print(matrix[rows][columns] + "\t");
}
}
}
This works,add a new line in for loop of the row. When the first row will be done printing the code will jump in new line.
ALL OF YOU PLEASE LOOT AT IT I Am amazed it need little IQ
just get length by arr[0].length and problem solved
for (int i = 0; i < test.length; i++) {
for (int j = 0; j < test[0].length; j++) {
System.out.print(test[i][j]);
}
System.out.println();
}

Categories