I need help with sorting Random numbers into a 2D array. I have to generate 50 random numbers into a column of the array, then sort the numbers in order (ascending or descending). This is what I have so far and am so lost. Please Help.
UPDATED VERSION
public static void main(String[] args)
{
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[i][j] = n;
}
}
int []temp;
for (int i=0;i<anArray.length;i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
if (anArray[i][j]>anArray[i][j+1])
{
temp =anArray[j];
anArray[j+1]=anArray[j];
anArray[j+1]=temp;
}
}
}
for (int i = 0; i < anArray.length; i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
System.out.println(anArray[i][j]);
}
}
}
}
You can sort 2D arrays on their initial element using a custom Comparator:
Arrays.sort(anArray, new Comparator<int[]>() {
public int compare(int[] lhs, int[] rhs) {
return lhs[0]-rhs[0];
}
});
First of all, you need nested for loops in order to properly insert the random numbers into the two dimensional array. I have also updated my response to show how the sorting should be done. Hope this helps!
EDITED TO SATISFY REQUIREMENTS MENTIONED IN COMMENT BELOW.
import java.util.Arrays;
import java.util.Random;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
//initialize the first row only
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[0][j] = n;
}
System.out.println("-----------Before the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
anArray = mySort(anArray);
System.out.println("-----------After the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
}
private static int[][] mySort(int[][] anArray) {
int [][] result = new int[anArray.length][anArray[0].length];
int thisRow[] = getRow(anArray, 0);
Arrays.sort(thisRow);
for(int j = 0; j < thisRow.length; j++){
result[0][j] = anArray[0][j];
result[1][j] = thisRow[j];
}
return result;
}
private static int[] getRow(int[][] anArray, int row) {
int thisRow[] = new int[anArray[row].length];
for(int j = 0; j < anArray[row].length; j++){
thisRow[j] = anArray[row][j];
}
return thisRow;
}
}
You can sort by considering the 2D array 1D. Let's consider a 3x4 array.
1st element's index is 0, 2nd is 1, 3rd is 2, 4th is 3, 5th is 4, etc.
General formula to convert from a 1D index to a 2D:
row_index = _1D_index % nRows;
col_index = _1D_index % nCols;
For example the 5th element has the 1D index of 4, to get the row: 4 % 3 = 1, to get the col, 4 % 4 = 0, so your element is at 1,0. What's the point of all this? Now you can just make a function
int GetAt(int index)
{
return array[index % nRows][index % nCols];
}
and something along the lines of:
void Swap(int index1, int index2)
{
int r1 = index1 % nRows;
int c1 = index1 % nCols;
int r2 = index2 % nRows;
int c2 = index2 % nCols;
int temp = array[r1][c1];
array[r1][c1] = array[r2][c2];
array[r2][c2] = temp;
}
And sort the array as if it was one dimensional :)
Related
I have a question. Can anyone help me with finding duplicates in submatrices?
I have a code which finds submatrices in 2d matrix, but I can't find duplicates. I thought to push the values onto the Stack (because in assignment I should use Stack), find all duplicates in each submatrix, and then compare them, but I don't really know how to do it. I'll be very gratefull, if anyone help me to finish this program.
My code:
public static void main(String[] args) throws Exception {
int[][] data = new int[3][3];
Random random = new Random();
for(int i=0; i<data.length;i++)
{
for(int j=0; j<data.length; j++)
{
data[i][j] = random.nextInt(10);
}
}
printSubMatrix(data);
}
private static void printSubMatrix(int[][] mat) {
int rows=mat.length;
int cols=mat[0].length;
Stack _stack = new Stack();
//prints all submatrix greater than or equal to 2x2
for (int subRow = rows; subRow >= 2; subRow--) {
int rowLimit = rows - subRow + 1;
for (int subCol = cols; subCol >= 2; subCol--) {
int colLimit = cols - subCol + 1;
for (int startRow = 0; startRow < rowLimit; startRow++) {
for (int startCol = 0; startCol < colLimit; startCol++) {
for (int i = 0; i < subRow; i++) {
for (int j = 0; j < subCol; j++) {
System.out.print(mat[i + startRow][j + startCol] + " ");
_stack.push(mat[i+startRow][j+startCol]);
}
System.out.print("\n");
}
System.out.print("\n");
}
}
}
}
System.out.printf(_stack.toString().replaceAll("\\[", "").replaceAll("]", ""));
}
public class Sort {
public static void main(String[] args) {
//fill the array with random numbers
int[] unsorted = new int[100];
for(int i = 0; i < 100; i++) {
unsorted[i] = (int) (Math.random() * 100);
}
System.out.println("Here are the unsorted numbers:");
for(int i = 0; i < 100; i++) {
System.out.print(unsorted[i] + " ");
}
System.out.println();
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = -1;
int hiIndex = -1;
for(int j = 0; j < 100; j++) {
if(unsorted[j] > hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = -1;
}
System.out.println("Here are the sorted numbers: ");
for(int i = 0; i < 100; i++) {
System.out.print(sorted[i] + " ");
}
System.out.println();
}
}
So this is in descending order but I want to reverse it.
I tried changing the if(unsorted[j] > hi) {
to a if(unsorted[j] < hi) {
[edit:changed greater than to less than, both were same]
Okay, you want the numbers to be in ascending order. So for descending, you assume that compared number would be -1 and all other number must be grater than this -1, now instead of -1 use the maximum value a number could be. Assign Integer.MAX_VALUE where you were assigning -1. So change your code like this:
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = Integer.MAX_VALUE;
int hiIndex = i;
for(int j = 0; j < 100; j++) {
if(unsorted[j] < hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = Integer.MAX_VALUE;
I have implemented a chain matrix multiplication. Although I get correct chain order, but while doing actual multiplication, the given multiply algorithm is not working properly. My Java Code:-
package algopackage;
import java.util.ArrayList;
import java.util.List;
public class ChainMatrixMultiplication {
static int s[][];
static int x[][];
static int y[][];
public ChainMatrixMultiplication() {
}
static void chainMatrixMultiplication(int[] p) {
boolean isFirst = false;
int n = p.length-1;
int m[][] = new int[n][n];
s = new int[n][n];
for (int c = 0; c < n; c++)
m[c][c] = 0;
for (int counter = 1; counter < n; counter++) {
for (int i = 0;i < n; i++) {
isFirst = false;
int j = i + counter;
for (int k = i; k < j && j < n; k++) {
int result = m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1];
if (!isFirst) {
m[i][j] = result;
s[i][j] = k;
isFirst = true;
} else if (m[i][j] > result) {
m[i][j] = result;
s[i][j] = k;
}
}
}
}
}
static int[][] matrixMultiply(List<Matrix> matrices, int s[][], int i ,int j) {
if (i ==j) return matrices.get(i).getMatrix();
else {
int k = s[i][j];
x = matrixMultiply(matrices, s, i, k);
y = matrixMultiply(matrices, s, k+1, j);
return mult(x,y);
}
}
static int[][] mult(int[][] x, int[][] y) {
int [][] result = new int[x.length][y[0].length];
/* Loop through each and get product, then sum up and store the value */
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < y[0].length; j++) {
for (int k = 0; k < x[0].length; k++) {
result[i][j] += x[i][k] * y[k][j];
}
}
}
return result;
}
public static void main(String[] args) {
int p[] = {5,4,6,2};
List<Matrix> matrices = new ArrayList<Matrix>();
Matrix m1 = new Matrix(5,4);
int arr[] = {1,2,40,2,3,29,10,21,11,120,23,90,24,12,11,1,11,45,23,21};
m1.addElementsToMatrix(5, 4, arr);
Matrix m2 = new Matrix(4,6);
int arr1[] = {1,1,1,2,3,12,12,3,10,12,12,29,22,11,22,11,11,11,13,1,2,12,4,2};
m2.addElementsToMatrix(4, 6, arr1);
Matrix m3 = new Matrix(6,2);
int arr2[] = {1,1,12,3,22,11,13,1,2,12,12,12};
m3.addElementsToMatrix(6, 2, arr2);
matrices.add(m1);
matrices.add(m2);
matrices.add(m3);
chainMatrixMultiplication(p);
matrixMultiply(matrices,s,0,2);
}
}
class Matrix {
private final int[][] matrix;
public Matrix(int rows, int cols) {
this.matrix = new int[rows][cols];
}
public void addElementsToMatrix(int rows, int cols, int[] arr) {
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = arr[counter++];
}
}
}
public int[][] getMatrix() {
return matrix;
}
}
In the above code matrixMultiply() function is throwing exception. Exception is caused as matrices are not being multiplied as expected. As recursion is not behaving as expected. I am missing something in this code. Any help will be appreciated.Thanks!
I'm not sure of the correctness of your code, but looking at the matrix multiplication output when you multiply matrix of dimension a*b and c*d after you multiply, you get a matrix of dimension a*d there by changing
for (int k = 0; k < x[0].length; k++) {
to
for (int k = 0; k < y[0].length; k++) {
should resolve the problem.
This:
x = matrixMultiply(matrices, s, i, k); // call A
y = matrixMultiply(matrices, s, k+1, j); // call B
return mult(x,y);
looks like it should multiply the result of call A by the result of call B. But in general, it doesn't.
x is not local, call B will usually overwrite it, except when call B immediately hits the base case.
This sort of thing tends to happen when you pass data around "to the side", not as function parameter or function return value. It is not reasonable to avoid that kind of data flow all the time, but you should avoid it here, especially since it's not even what you wanted.
Here I have integer array contains 81 values so that I need to store 9 values per array total I need to get 9 arrays. Eg: array1 from 1 to 9 and array2 from 10 to 18 and array3 from 19 to 27 like that. Can anybody help me how to get this values?
public class demo {
public static void main(String[] args) {
int num = 81;
int numArray = num / 9;
int[] input = new int[num];
for (int i = 0; i < num; i++) {
input[i] = i + 1;
}
for (int j = 0; j < input.length; j++) {
System.out.println(input[j]);
}
}
}
How to get desired result?
You can use System#arraycopy():
int[] first_part = new int[27];
int[] second_part = new int[27];
int[] third_part = new int[27];
System.arraycopy(input, 0, first_part, 0, 27);
System.arraycopy(input, 27, second_part, 0, 27);
...
I've just noticed that you want 9 parts, you can easily put this in a loop and use arraycopy.
public static void main(String[] args) {
int num = 85;
int limit = 5;
int index = 0;
int extra = 0;
int finalArrayIndex = 0;
int[] innerArray = null;
int[] input = new int[num];
boolean isEnd = false;
if (num % limit > 0) {
extra = 1;
}
int[][] finalArray = new int[(num / limit) + extra][limit];
for (int i = 0; i < input.length; i = i + (limit)) {
innerArray = new int[limit];
for (int j = 0; j < limit; j++) {
innerArray[j] = input[index++];
if (index >= input.length) {
isEnd = true;
break;
}
}
finalArray[finalArrayIndex++] = innerArray;
if (isEnd) {
break;
}
}
// just for test
for (int k = 0; k < finalArray.length; k++) {
for (int l = 0; l < finalArray[k].length; l++) {
System.out.println("finalArray[" + k + "]" + "[" + l + "] : "
+ finalArray[k][l]);
}
}
}
This is dynamic solution, you can change value of num and limit variables. I hope this will help you :)
Java Fiddle link : http://ideone.com/jI8IOb
My suggestion is use subList
You can follow these steps.
Store all 81 values in a List (ArrayList)
Then create 9 sub List from that using subList()
You can convert List to array.
List<Integer> fullList=new ArrayList<>();
List<Integer> list1=fullList.subList(0,8); // first 9 elements
Integer[] bar = list1.toArray(new Integer[list1.size()]);
im new to this but im tring to do a hotel reservation program.
So i have a 2D int array with ALL rooms, when i start the program i want them to be randomly shuffle in to an array called RoomNotInUse or RoomInUse (so evertime i start the program the rooms are randomly generated.
Would be awesome if anyone know a way around this :)
// ARRAYS
protected static int[][] rooms = {
{1,1}, {1,2}, {1,3}, {1,4}, {1,5},
{2,1}, {2,2}, {2,3}, {2,4}, {2,5},
{3,1}, {3,2}, {3,3}, {3,4}, {3,5},
{4,1}, {4,2}, {4,3}, {4,4}, {4,5},
{5,1}, {5,2}, {5,3}, {5,4}, {5,5}
};
//Declare all hotel rooms 5x5, the first number is the floor and the sec is the room
private char[][] ROIU = {
};
//Rooms not in use
private char[][] RIU = {
};
//Rooms in use
public class roomShuffle {
}
//Shuffle all rooms in 2 diffrent arrays, ROIN and RIU
public class RoomNotInUse {
}
//Displayes all the rooms thats not in use
public class RoomInUse {
}
//Displayes all rooms in use
}
You can use Fisher–Yates algorithm modified for two-dimensional arrays:
void shuffle(int[][] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
for (int j = a[i].length - 1; j > 0; j--) {
int m = random.nextInt(i + 1);
int n = random.nextInt(j + 1);
int temp = a[i][j];
a[i][j] = a[m][n];
a[m][n] = temp;
}
}
}
Assign all array into list. Than use Collections.shuffle().
List<int[]> pair=new ArrayList<int[]>();
pair.addAll(Arrays.asList(rooms));
Collections.shuffle(pair);
You can use shuffle-
Collections.shuffle()
Here's a tutorial that describes with or without Collections.
A generic shuffle method in Java should me similar to this
The important thing is that you have to swap an item with a random element that comes after in the collection ;)
public void shuffle(Comparable [] a){
for(int i=0;i,a.length;i++)
swap(a,i,getRandom(i,a.length-1);
}
private int getRandom(int min, int max){
Random rnd = new Random();
return min + rnd.nextInt(max-min+1);
}
private void swap(Comparable [] a, int i, int j){
Comparable temp = a[i];
a[i]=a[j];
a[j]=temp;
}
Otherwise you can use the Collection.shuffle method.
Scanner scanner = new Scanner(System.in);
int n;
int m;
int selection;
System.out.println("Enter number of team");
n = scanner.nextInt();
m = (int) Math.sqrt(n);
int[][] matrix = new int[m][m];
List<Integer> listMatrix = new ArrayList<Integer>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = i * m + j + 1;
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
for (int i = 0; i < m * m; i++) {
listMatrix.add(i + 1);
}
System.out.println();
do {
System.out.println("what line is the card?");
selection = scanner.nextInt();
} while (!(selection >= 1 && selection <= m));
selection -= 1;
int[] values = new int[m];
for (int i = 0; i < m; i++) {
values[i] = matrix[selection][i];
// System.out.print(values[i] + "\t");
}
System.out.println();
Collections.shuffle(listMatrix);
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = listMatrix.get(j + i * m);
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
scanner.close();