This is the assignment: Write a method that sorts the elements of a matrix with 2 dimensions. For example
sort({{1,4}{2,3}})
would return a matrix
{{1,2}{3,4}}.
I dont know what im doing wrong in my code cause the output i get is 3.0, 3.0, 4.0, 4.0.
This is what i have so far any help would be appreciated.
public static void main(String[] args) {
double[][] array = { {1, 4}, {2, 3} };
double[][] new_array = sort(array);
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
System.out.print(new_array[i][j] + " ");
}
}
}
public static double[][] sort(double[][] array) {
double[] storage = new double[array.length];
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
storage[i] = array[i][j];
}
}
storage = bubSort(storage);
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
array[i][j] = storage[i];
}
}
return array;
}
public static double[] bubSort(double[] list) {
boolean changed = true;
double temp;
do {
changed = false;
for (int j = 0; j < list.length -1; j++)
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
changed = true;
}
} while (changed);
return list;
}
}
The main problem that you are experiencing is how you are copying the values from the 2d array into the 1d array. You are actually only copy two values into an array of length 2. The length of a 2d array is not the full m x n length.
I will give a small hint how you can go about copying from the 2d array into the 1d array, but it is up to you to figure out how to copy back from the 1d array into the 2d array. Also, how would you go about finding the full length of the array?
double[] storage = new double[4];//You should calculate this value
int k = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
storage[k++] = array[i][j];
}
}
Your bubble sort works fine, but then you are copying the values back wrong. Try printing the array storage after the sort and you will see that it is now correct.
You are overwriting your storage array you have it set to array[i]. Because it is in the for loop you are setting storage[0] = array[0][0] then setting storage[0] = array[0][1]. This causes you to only pick up the last number in that dimension of the array. Likewise, when you are reading them back out you are inserting the same number twice. Since 4 and 3 are the last two numbers in their respective dimensions this shows that you are sorting the array. You need a for loop for storage that is set < array.length and store your values inside that.
Related
I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not.
Can't find a mistake right here:
public int[][] flipAndInvert(int[][] A) {
int row = -1;
int col = -1;
int[][] arr = A;
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length - 1; j >= 0; j--) {
col++;
arr[row][col] = A[i][j];
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
}
}
return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };
After proceeding the output should be:
After inverting:
{1,1,0},{1,0,0},{0,0,0}
After flipping:
{0,0,1,},{0,1,1},{1,1,1}
Thanks to all a lot, the problem was here:
int[][] arr = A;
The reference of the array is being passed to arr.
What I think is that since you are using this line:
int[][] arr = A;
The reference of the array is being passed to arr, and hence the line:
arr[row][col] = A[i][j];
is equivalent to:
A[row][col] = A[i][j];
as arr has an reference to A and they both now refer to the same memory location (or they are both different names to a single variable)
You can fix this by either using the new keyword with arr and then initializing it:
int[][] arr = new int[someRows][someCols];
//use for loop to assign the value to each element of arr
Or you can run the for loop till arr[i].length/2 - 1:
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length / 2 - 1; j >= 0; j--) { //here changed arr[i].length to arr[i].length / 2
col++;
arr[row][col] = A[i][j]; //for this you do not need arr and you can directly work on A and return it
}
}
The problem of your code should be this line:
int[][] arr = A;
You are assigning the reference of array A to arr and from then when you modify one you modify both of the arrays or better they are modified together because they refer to the same address.
Using apache commons lang:
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 3 * i;
matrix[i][1] = 3 * i + 1;
matrix[i][2] = 3 * i + 2;
}
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
ArrayUtils.reverse(matrix);
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
Hope this helps.
I am trying to create a program, which counts the minimum of each dimension in a two dimensional array. So for ex. if i had an array:
int[][] test = {{1,2,3},{2,3,4},{4,5,6}}
the program would display: [1,2,4] - the minimum of each dimension.
For that I've created a method called minimum, which looks like this
static int[] minimum(int[][] arr) {
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
int min = arr[i][0];
if(arr[i][j] < min) {
min = arr [i][j];
result [i] = min;
} else{
}
}
}
return result;
}
But when i call out this method in my main, with a sample array
public static void main(String[] args) {
int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};
System.out.println(Arrays.toString(minimum(arr)));
}
The program displays [0,0,0,]. Do You have any clue where is the problem and how to fix it?
The problem is that if the first element in the array is min, it never gets recorded to the result array. Try:
static int[] minimum(int[][] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i][0];
for (int j = 1; j < arr[i].length; j++) {
if (arr[i][j] < result[i]) {
result[i] = arr[i][j];
}
}
}
return result;
}
Note that there needs to be at least one element per row in the input matrix for the above function; add a conditional or use Integer.MIN_VALUE to handle empty rows if you wish.
This should work. You reset the min to the first element every time. So you are basically comparing if there is any value smaller than the first one.
static int[] minimum(int[][] arr){
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++){
result[i] = Integer.MAX_VALUE;
for(int j = 0; j < arr[i].length; j++){
if(arr[i][j] < result[i]) {
result [i] = arr[i][j];
}
}
}
return result;
}
I have an ArrayList and I want to create a method that will turn it into a 2d array, int[][].
This new 2d array will represent a matrix and it has to be square, so for example if I use [8, 2, 3, 0] the ressult will be {8,2}
{3,0}
public static int[][] convertIntegers(ArrayList<Integer> integers){
int m = (int) Math.sqrt(integers.size());
int[][] ret = new int[m][m];
int cont = 0;
for(int i=0; i<m+1 ; i++)
{
for(int j=0; j<m; j++)
{
cont = cont + 1;
ret[i][j] = integers.get(cont);
;
}
}
return ret;}
Your implementation is almost ok, except for some off-by-one errors:
You need to increment cont after the integers.get call, not before. If you increment before, then the first element of the list will be skipped. An easy way to fix that is to move the incrementing inside the inner loop, counting it together with j.
The outer loop should go until i < m instead of i < m + 1
With the errors fixed:
for (int i = 0, cont = 0; i < m; i++) {
for (int j = 0; j < m; j++, cont++) {
ret[i][j] = integers.get(cont);
}
}
Btw, another way is without using cont at all,
calculating the correct position using i, j and m:
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = integers.get(i * m + j);
}
}
I have an input String, which has a size of 9 or 16 or 25... (So always a number which has an integer root.)
I need to create a 2 dimensional matrix from it, which I would like to store in a two dimensional array. I know how to store it in a one dimensional array, but I don't know how to upload the two dimensional array with the elements of the string in a correct way.
It would be something like this:
(Let's assume we have 9 characters now)
String Matrix[][] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
But the order would be this:
1 2 3
4 5 6
7 8 9
I guess I would use two 2 for loop but not sure about it.
A good approach would be calculating the square root of the string length: that way you would find out which is the Matrix sizes, and then split up the string in the "rows" or "columns" you want for your matrix.
int matrixSize = Math.sqrt(input.length());
for(int i = 0; i<matrixSize; i++) {
for(int j = 0; j<matrixSize; j++){
matrix[i][j] = input[j];
j++;
}
}
Swap i and j in the matrix to switch rows for columns.
Hope this helps.
try this
string s="123456789";
int n=new int[3][3],p=0;
for(int i = 0; i<3; i++)
for(int j = 0; j<3; j++){
matrix[i][j] =Integer.parseInt(s[p]);
P++;
}
you may edit dimensions of 2-d array accordingly.
String input = "1,2,3,4,5,6,7,8,9";
String[] numbers = input.split(",");
int size = (int) Math.sqrt(numbers.length);
String[][] matrix = new String[size][size];
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
matrix[i][j] = numbers[i * size + j];
}
}
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Lets guess your input will be like :
String input="1,2,3,4,5,6,7,8,9";
Then you can do something like :
String[] inputArray=input.replace("\"", "").split(",");
for (int i = 0; i < inputArray.length; i++) {
System.out.println(inputArray[i]);
}
int matrixSize=(int) Math.ceil(Math.sqrt(inputArray.length));
int i,j;
int index=0;
for(i=0;i<matrixSize;i++)
{
for(j=0;j<matrixSize && index<inputArray.length;j++,index++)
System.out.print(inputArray[index]);
System.out.println("");
}
It will work for any number of input.
I need a simple java program that can generate me the custom sets for a set,say for {'1','2','3','4'}. The result should be:
{'1','2'},{'2','3'},{'3','4'},{'1','2','3'},{'2','3','4'}.
I have tried codes for powerset,but the output isn't desirable. It would be appreciable if the code could be something like:
for(j=2;j<set.size()-1;j++)
{
for(i=0;i<set.size()-1;i++)
{
//a[i],a[i+1] when j=2
//a[i],a[i+1],a[i+2] when j=3
}
}
I know .size() is for ArrayList and a[i] is for simple array and i've written both as any approach will do!! Thanks In Advance!! :)
This code should print the values you want:
final int[] values = {1, 2, 3, 4};
for (int size = 2; size < values.length; size++) {
for (int i = 0; i + size <= values.length; i++) {
for (int j = 0; j <= size - 1; j++) {
System.out.print(values[i + j]);
}
System.out.println();
}
}
From the example, we see that you want to print sets of values whose length is greater than 1 and smaller than the total set, so that 's what the following line does:
for (int size = 2; size < values.length; size++) {
After that we compute the starting index of the subset, watching not to run into a IndexArrayOutOfBounds exception (see the line below)
for (int i = 0; i + size <= values.length; i++) {
From there we just print the values starting at i index and with the subset length of size
for (int j = 0; j <= size - 1; j++)
This is the sample code which is generating the desired result:
int[] array = { 1, 2, 3, 4 };
int size = 2;
for (int j = 0; j < array.length; j++) {
for (int i = 0; i <= array.length - size; i++) {
int[] temp = Arrays.copyOfRange(array, i, i + size);
for (int x : temp) {
System.out.print(x + ",");
}
System.out.println();
}
size++;
if (size == array.length) {
break;
}
}
Output:
1,2,
2,3,
3,4,
1,2,3,
2,3,4,