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 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 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.
package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
this is a really simple program but for some reason, the array for the traincars goes out of bounds..
Why is this happening?
The problem is here:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
When i equals traincars-1 you will be accessing elements i+1, i+2. and i+3 which are out of bounds of your trains array.
If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:
for(int i = 0; i < traincars - 3; i++) {...}
In the last iteration of
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
You try to access trains[i+1] and this is bigger than the length of your trains array.
To make this for loop matter you should just do the following:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}
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();