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();
Related
I am trying to sort an array of random numbers without using the arrays.sort. I have the code, but it doesn't work. not sure where is the error. Any kind of help is appreciated.
import java.util.*;
public class Sort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you want? ");
int howMany = in.nextInt();
int [] myArray = getRandomArray(howMany);
}
/* public static int bsearch(int[] arr, int key)
{
}*/
public static int[] getRandomArray(int howMany) {
int[] returnMe = new int[howMany]; // Assume size >= 0
Random rand = new Random();
for (int i = 0; i < howMany ; i++)
returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
//System.out.print(returnMe[i] + " ");
for (int i = 1; i <= (howMany - 1); i++)
{
for (int j = 0; j < howMany - i -1; j++)
{
int tmp = 0;
if (returnMe[j] > returnMe[j+1])
{
tmp = returnMe[j];
returnMe[j] = returnMe[j + 1];
returnMe[j + 1] = tmp;
}
}
}
for ( int i = 0; i < howMany; i++)
System.out.println(returnMe[i] + " ");
return returnMe;
}
}
Your line
for (int j = 0; j < howMany - i -1; j++)
should be
for (int j = 0; j <= howMany - i -1; j++)
or alternatively, remove the "-1" and keep "<". Otherwise, you will ignore the last number in the array. Everything else looks fine to me.
I need to write a program that produces a single random permutation of the numbers 1 - 10. If possible, no methods or extra include libraries. Simple as can be. Here is what I have so far.
import java.util.Scanner;
public class SwitchingNum {
public static void main(String[] args) {
int num = 10;
Scanner in = new Scanner(System.in);
int[] tempArray = new int[10];
int currentSize = tempArray.length;
System.out.print("First Array: ");
for(int i = 0; i < num; i++){
tempArray[i] = i + 1;
System.out.print(tempArray[i] + " ");
}
int[] permArray = new int[tempArray.length];
System.out.println();
System.out.print("Second Array: ");
for (int i = 0; i < permArray.length; i ++){
permArray[i] = tempArray[(int) (Math.random() * currentSize -1)];
for (int j = i; j < currentSize -1; j++){
tempArray[i] = tempArray[i+1];
}
currentSize--;
System.out.print(permArray[i] + " ");
}
}
}
An easy way to shuffle an array is the Fisher–Yates shuffle. Just copy the original array into your permArray and then do:
Random rand = new Random();
for(int i = 0; i < permArray.length - 1; i++) {
int swapPosition = rand.nextInt(permArray.length - i) + i;
int tmp = permArray[i];
permArray[i] = permArray[swapPosition]
permArray[swapPosition] = tmp;
}
Don't forget to import java.util.Random. For more info, you can take a look at this question.
I have this assignment for my class where I have to create a Matrix Multiplication program. Here's the condition:
Implement two types of algorithms for multiplying two n × n matrices. Assume n is a power of 2:
The straight-forward O(n^3) matrix multiplication algorithm.
Strassen’s matrix multiplication algorithm.
Evaluate your different algorithms, and write a short report. Create test matrices for different values of n (4, 10, 20,100). Generate matrices using random numbers. Compute the running time of your algorithms. Your report should include the running times and conclusions.
Here's my code so far:
public class MatrixMultiplication
{
public static void main(String[] args)
{
Random rand = new Random();
int rows = rand.nextInt(7) + 2;
int columns = rand.nextInt(7) + 2;
System.out.println("The matrix has " + rows + " randomized rows");
System.out.println("The matrix has " + columns + " randomized column");
System.out.println();
double[][] a = new double[rows][columns];
double[][] b = new double[columns][rows];
System.out.println("The first matrix has the values: ");
Matrix m1 = new Matrix(a);
System.out.println("---------------------------------");
System.out.println("The second matrix has the values: ");
Matrix m2 = new Matrix(b);
System.out.println();
Matrix productRegular = m1.multiply(m2);
}
}
And here's my other class:
import java.util.Random;
class Matrix
{
double[][] arrayA;
double[][] arrayB;
private Matrix(double[][] a, double[][] b)
{
arrayA = a;
arrayB = b;
}
public Matrix(double[][] array) //Create matrix values
{
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
}
public double multiply(double[][] a, double[][] b)
{
double[][] c = new double[a.length][b[0].length];
System.out.println("Product of A and B is");
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < a[0].length; k++)
{
c[i][j] += a[i][k] * b[k][j];
System.out.println(c[i][j] + " | ");
}
}
System.out.println();
}
return c;
}
}
I know I have to pass an object/Matrix for the multiply method, but how would I do that? There are other concerns in my code, but I want to focus on passing objects right now.
Let's take a deep look to your code:
Why do you have two double[][] inside the Matrix class? A Matrix is just one bidimensional array. You should delete the arrayB
double[][] arrayA;
double[][] arrayB;
What's the point of the private constructor? For you, it is useless right now.
private Matrix(double[][] a, double[][] b)
{
arrayA = a;
arrayB = b;
}
In the public constructor, you are printing a Matrix, but you are not saving anywhere.
public Matrix(double[][] array) //Create matrix values
{
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
arrayA = array;
}
Anyway, I think it would be much better to make 2 constructors
public Matrix(double[][] array) //you just pass an array created outside the class
{
arrayA = array;
}
public Matrix(int rows, int columns) //Create matrix values
{
double[][] array = new double [rows][columns];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
arrayA = array;
}
Why your multiply method have 2 parameters? As it is inside the class Matrix (that have a double[][]variable). You only need a parameter (I think it is better to your example to have a Matrix parameter instead of a double[][]parameter and return also a Matrix).
I don't like printing when you are creating or multiplying. It's much better to create a method to print the Matrix, and calling it when you want to print them.
So....the final code would be something like this:
Main
public class MatrixMultiplication
{
public static void main(String[] args)
{
Random rand = new Random();
int rows = rand.nextInt(7) + 2;
int columns = rand.nextInt(7) + 2;
System.out.println("The matrix has " + rows + " randomized rows");
System.out.println("The matrix has " + columns + " randomized column");
System.out.println();
System.out.println("The first matrix has the values: ");
Matrix m1 = new Matrix(rows,columns);
m1.print();
System.out.println("---------------------------------");
System.out.println("The second matrix has the values: ");
Matrix m2 = new Matrix(columns, rows);
m2.print();
System.out.println();
System.out.println("Product of A and B is");
Matrix productRegular = m1.multiply(m2);
productRegular.print();
}
}
Matrix Class
import java.util.Random;
class Matrix
{
double[][] arrayA;
public Matrix(double[][] array) //Create matrix values
{
arrayA=array;
}
public Matrix(int rows, int columns) //Create matrix values
{
double[][]array= new double[rows][columns];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
}
}
arrayA=array;
}
public Matrix multiply(Matrix m)
{
double[][]b=m.arrayA;
double[][] c = new double[arrayA.length][b[0].length];
for(int i = 0; i < arrayA.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < arrayA[0].length; k++)
{
c[i][j] += arrayA[i][k] * b[k][j];
}
}
}
return new Matrix(c);
}
public void print(){
for(int i=0;i<arrayA.length;i++){
for(int j=0;j<arrayA[0].length;j++){
System.out.print(arrayA[i][j] + " | ");
}
System.out.println();
}
}
}
I am trying to solve question at Reverse Game
When I submit my code, in some of the testcases it is getting timeout.
I think problem may be in reverseSubArray() method but I am not sure how to improve performance here.
Following is my code:
public class ReverseGame
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
int[] numberOFBalls = new int[testCases];
int[] ballNumberArray = new int[testCases];
for (int i = 0; i < testCases; i++)
{
numberOFBalls[i] = scanner.nextInt();
ballNumberArray[i] = scanner.nextInt();
}
for (int i = 0; i < testCases; i++)
{
process(numberOFBalls[i], ballNumberArray[i]);
}
scanner.close();
}
private static void process(int totalNumberOFBalls, int ballNumber)
{
int[] ballsArray = new int[totalNumberOFBalls];
int maximumNumberOnBall = totalNumberOFBalls - 1; // This is because
// balls are numbered
// from 0.
// As the first step is to reverse the Balls arrangement, So insert into
// ballsArray in descending order of index.
for (int i = 0; i < totalNumberOFBalls; i++)
ballsArray[i] = maximumNumberOnBall--;
for (int i = 1; i < totalNumberOFBalls; i++)
{
ballsArray = reverseSubArray(ballsArray, i);
}
int position = findPosition(ballsArray, ballNumber);
System.out.println(position);
}
private static int[] reverseSubArray(int[] a, int fromIndex)
{
int temp = 0, counter = 1;
int midIndex = (a.length - fromIndex) / 2;
for (int i = fromIndex; i < fromIndex + midIndex; i++)
{
temp = a[a.length - (counter)];
a[a.length - (counter)] = a[i];
a[i] = temp;
counter++;
}
/*
* System.out.println(); for (int i = 0; i < a.length; i++)
* System.out.print(a[i] + " ");
*/
return a;
}
private static int findPosition(int[] ballsArray, int ballNumber)
{
for (int i = 0; i < ballsArray.length; i++)
{
if (ballsArray[i] == ballNumber)
return i;
}
return 0;
}
}
The time complexity of your solution is O(n ^ 2). It is too slow for n = 10 ^ 5. So you need to use a better algorithm. Here is simple linear solution which uses the fact that we do not need to know the positions of all balls(we need only the k-th):
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int testsCount = in.nextInt();
for (int t = 0; t < testsCount; t++) {
int n = in.nextInt();
int k = in.nextInt();
// Simulates all rotations,
// but keeps track only of the k-th ball.
// It does not matter what happens to the others.
for (int i = 0; i < n; i++)
if (k >= i)
k = i + n - 1 - k;
out.println(k);
}
out.flush();
}
}
This solution has an O(n) time complexity and easily passes all test cases.
It is actually possible to find the positions of all balls in linear time, but it is not required here.
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 :)