explaining this simple program - bucket sort - java

What does int[] a do in this code?
public class BucketSort_main {
public static void main(String[] args) {
int[] numbers = new int [5]; //create an array to house the numbers generated
int[] sortedArray = new int [5]; //create array to be a temp housing for the numbers
int [][] bucket = new int [10][numbers.length]; //creates 2D array of 0-9
int [] a = new int [10];
int divisor = 1;
int digitCount = 1;
boolean moreDigits = true;
//fill the array and array to be sorted with the random numbers 0 - 100
for (int i = 0; i < numbers.length; i++) {
numbers [i] = (int)(Math.random()*100);
sortedArray [i] = numbers [i];
}
System.out.println("UnSorted Numbers");
for (int i = 0; i< numbers.length; i++){
System.out.println (numbers[i]);
}
}
System.out.println("\n");
int[] tempArray = new int[10]; //creatE a temp array of size equal to the amount of buckets
while (moreDigits) {
moreDigits = false;
for (int i = 0; i < tempArray.length; i++){
tempArray[i]= -1; //initailze to make sure a null pointer is not hit
}
for (int i = 0; i < numbers.length; i++){
int tmp = sortedArray[i] / divisor; //create a temp int of the array value / divisor to get its single digit value
if (tmp/10 != 0){
moreDigits = true;
}
int numPlace = tmp % 10;
tempArray[numPlace] = sortedArray[i]; //at the digits "ones"/tens value for row index, set the number from the sorted array into that index
bucket [numPlace][a[numPlace]] = sortedArray[i]; //place the numbers into the proper coord of the bucket.
//Print statements used for DEBUGGING
System.out.println("Number: " + tempArray[numPlace] +" Has Digit "+digitCount+" equal to "+ numPlace);
// bucket [digit][a[digit]] = tempArray[i];
//row may seem "off" to user, but the row prints based on 0 - n
System.out.println ("Digit " + numPlace + " moved into row " + a[numPlace] + ". " + bucket[numPlace][a[numPlace]]);
System.out.println (" ");
a[numPlace]++;
}
digitCount++;
divisor *= 10; //multipy the divisor by 10 to move to the next 1s. 10s, or 100s place
int j = 0; //iteration for tempNumbersArray
for (int x = 0; x < 10; x++) {
a[x] = 0;
for (int y = 0; y < numbers.length; y++){
if (bucket[x][y] != 0) {//see if value in bucket is a zero, if it is dont print it
sortedArray [j] = bucket[x][y]; //set sorted array value equal to the value at row/col index of bucket
bucket[x][y] = 0; //set that spot that was just copied over to zero
j++; //increment to the next index of sorted array
}
}
}
} //end while
System.out.println("Sorted Numbers:");
for (int i = 0; i < numbers.length; i++) {
System.out.println (sortedArray[i]);
}
}

The 'a' array holds the number of entries that a certain bucket holds. Each time something is added to bucket x, the value of a[x] is incremented with one.
So 'a' is only used to do some bookkeeping. This can be avoided by changing
bucket [numPlace][a[numPlace]] = sortedArray[i];
in
bucket [numPlace][bucket[numPlace].length] = sortedArray[i];
and
System.out.println ("Digit " + numPlace + " moved into row " + a[numPlace] + ". " + bucket[numPlace][a[numPlace]]);
in
System.out.println ("Digit " + numPlace + " moved into row " + bucket[numPlace].length + ". " + bucket[numPlace][a[numPlace]]);
and by removing
a[numPlace]++;

Related

Finding the 10 highest frequencies in a randomized array-Java

The project description is to create an array of 1000 randomized numbers from 1-50 and to display the 10 highest numbers by frequency. I cut down the numbers in my code for easier testing.
I have created the array with randomized numbers and displayed how many times each number occurred.
I am having trouble figuring out how to sort the numbers from highest highest to lowest.
Any help would be appreciated.
import java.util.*; //import random class and arrays
class MaxArray{
public static void main(String[]args){
Random rand = new Random(1); //create random object and sets seed to one
int[] randArray = new int [51];
int[] newArray = new int[51];
for(int i = 0; i < randArray.length; i++){
randArray[i] = rand.nextInt(50) + 1; // returns a single random integer between 1 and 50
}
Arrays.sort(randArray);
System.out.println(Arrays.toString(randArray));
for(int j = 0; j < randArray.length; j++){
newArray[randArray[j]] += 1;
}
System.out.println(Arrays.toString(newArray));
for(int k = 0; k < newArray.length; k++){
System.out.println("Number " + k + " occurred " + newArray[k] + " times");
}
}// end main
}//end class
This is how you get from highest to lowest
for (int i = randArray.length-1; i >=0 ; i--) {
System.out.print(randArray[i]+" ");
}
and this is how you find 10 highest numbers:
int CheckingDublicate = 0, count = 1;
for(int i = 1; i <= randArray.length; i++){
if(count<=10{
if(CheckingDublicate!=randArray[randArray.length-i])
{
//Ignoring if dublicate
System.out.print(randArray[randArray.length-i]+" ");
CheckingDublicate = randArray[randArray.length-i];
count++;
}
}
else
break;
}

How to Return Single-Digit Counts after Numbers are Randomly Generated (Java,Arrays)

I have written a program that generates 100 random integers between
0 and 9 and displays the count for each number.
int[] counts = new int[10]; // Array of ten integers
// Store the counts of 100 random numbers
for (int i = 1; i <= 100; i++) {
counts[(int)(Math.random() * 10)]++;
}
// Display the results
System.out.println("Count for each number between 0 and 9:");
for (int i = 0; i < counts.length; i++) {
System.out.println(i + "s: " + counts[i]);
}
Now I am being asked to write a program that generates 1000 random integers between 0 and 99, and display the number of times each single-digit number (i.e. 0, 1, 2, ..., 9) was generated. How can I modify this code to do that?
Update:This code is now fixed. Here is the updated version for anyone who needs it. Thanks to everyone who responded so fast!
int[] counts = new int[100];
for (int i = 1; i <= 1000; i++) {
counts[(int)(Math.random() * 100)]++;
}
System.out.println("Count for each number between 0 and 9:");
for (int i = 0; i < 10; i++) {
System.out.println(i + "s: " + counts[i]);
}
Instead of relying on magic numbers, extract the values which drive your logic. The maximum number and the count are what is changing. Make those variables. Then you only have to modify the value of the variable if they change again in the future. Like,
final int numberCount = 1000;
final int max = 99;
int[] counts = new int[max + 1];
for (int i = 0; i < numberCount; i++) {
counts[(int) (Math.random() * (max + 1))]++;
}
System.out.println("Count for each number between 0 and 9:");
for (int i = 0; i < 10; i++) {
System.out.println(i + "s: " + counts[i]);
}

How to find the exact location of a maximum and minimum number in a matrix

How to find the exact location of a maximum and minimum number in a matrix. The code can display the max and min values in the matrix but I need to find the exact location such as row and columns. Needs to be formatted like this. The maximum number is 2 at row 0, column 3.
import java.util.Scanner;
public class alarconh_Program2 {
public static void main(String[] args){
Scanner input = new Scanner (System.in);
int row = 0;
int col = 0;
double col1sum,col2sum,col3sum,col4sum,col1avg,col2avg,col3avg,col4avg;
System.out.println(" (Col) x (Row) ");
System.out.println("Enter the number of rows");
row = input.nextInt();
System.out.println("Enter the number of columns");
col = input.nextInt();
double [][] matrix = new double[row][col];
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
matrix [i][j] = input.nextDouble();
}
}
System.out.println();
String formathd="The Matrix is";
System.out.printf(formathd);
for (int i1 = 0; i1 < matrix.length; i1++){
System.out.println();
for(int j1 = 0; j1 < matrix[i1].length; j1++){
String Table=" %2.1f ";
System.out.printf(Table, matrix [i1][j1]);
}
}
col1sum = matrix[0][0] + matrix[1][0] + matrix[2][0];
col2sum = matrix[0][1] + matrix[1][1] + matrix[2][1];
col3sum = matrix[0][2] + matrix[1][2] + matrix[2][2];
col4sum = matrix[0][3] + matrix[1][3] + matrix[2][3];
System.out.println();
String SUM = "%2.1f %2.1f %2.1f %2.1f :SUM";
System.out.printf(SUM,col1sum,col2sum,col3sum,col4sum);
col1avg= col1sum/row;
col2avg = col2sum/row;
col3avg = col3sum/row;
col4avg = col4sum/row;
System.out.println();
String AVG = " %2.1f %2.1f %2.1f %2.1f :AVG";
System.out.printf(AVG,col1avg,col2avg,col3avg,col4avg);
System.out.println();
double maxValue = Integer.MIN_VALUE;
for (int i2 = 0; i2 < matrix.length; i2++)
for (int j2 = 0; j2 < matrix[i2].length; j2++)
if (matrix[i2][j2] > maxValue)
maxValue = matrix[i2][j2];
System.out.println("Maximum numbers is " +maxValue + " at row " +row+ ", and column " +col);
double minValue =Integer.MAX_VALUE;
for (int i2 = 0; i2 < matrix.length; i2++)
for (int j2 = 0; j2 < matrix[i2].length; j2++)
if (matrix[i2][j2] < minValue)
minValue = matrix[i2][j2];
System.out.println("Minimum numbers is " +minValue+ " at row " +row+ ", and column " +col);
}
}
if you want to print the exact location of minimum and maximum, edit your last loop to this :-
for (int i2 = 0; i2 < matrix.length; i2++)
for (int j2 = 0; j2 < matrix[i2].length; j2++)
if (matrix[i2][j2] < minValue)
{
minValue = matrix[i2][j2];
row = i2; // stores the current row to row variable
col = j2 // stores current columb to col variable
}
System.out.println("Minimum numbers is " +minValue+ " at row " +row+ ", and column " +col);
max=m[0][0];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(m[i][j]>max)
{
max=m[i][j];
row = i;
col = j;
}
}
}
System.out.println("Maximum element in matrix is "+max+" at m["+row+"]["+col+"]");
//MINIMUM element of the matrix
min=m[0][0];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(m[i][j]<min)
{
min=m[i][j];
row = i;
col = j;
}
}
}
System.out.println("Minimum elementin matrix is "+min+" at m["+row+"]["+col+"]");
For larger matrices, an O^2 approach is going to be cost prohibitive.
Could also maintain metadata as the matrix is populated. For an r(ow) x c(olumn) matrix, create an additional single-dimension array of size c and whenever a new max value is put into row n, update the additional array for index n with the c of the new largest value.
It's a trade-off between memory and processing, but for a non-trivial use case it's likely going to be faster.

Multidimensional Array Java

I am writing a program using a method that returns the location of the largest element in a two dimensional array.
Example:
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
My code is working, but I'm getting the output wrong. Instead of numbers I am getting some weird output with letters and numbers. How can I fix it? Thanks!
My code
import java.util.Scanner;
public class homework1a {
public static int[] locateLargest(double[][] a)
{
int total = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
maxRow = i;
maxColumn = j;
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
double b = 0;
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
}
System.out.println("The location of the largest element is at "+ locateLargest(a));
}
}
Your method locateLargest() returns an int-array, which you are implicitly converting to string while printing it.
I think you want to display the row and cell numbers inside the array:
int[] largest = locateLargest(a);
System.out.println(String.format("The location of the largest element is at %d,%d", largest[0], largest[1]));
locateLargest(a) returns an int[2]. Arrays cannot be converted to strings natively, so the default toString() implementation is invoked on the array. The returned string representation does not contain the array elements.
This question might help you to print a helpful representation of the array. You might also want to print both values independently, not the array as a whole, e.g. like this:
int[] pos = locateLargest(a);
System.out.println("The location of the largest element is at " + pos[0] + ":" + pos[1]);
To print Arrays use Arrays.toString(array) output will be like [x,y]
System.out.println("The location of the largest element is at "+ Arrays.toString(locateLargest(a)));
Your method locateLargest returns an int[] which will not be printed out nicely.
If you want to keep the signature of locateLargest as it is, you could change your code in main like this:
int[] positionOfLargest = locateLargest(a);
System.out.println("The location of the largest element is at " +
positionOfLargest[0] + "/" + positionOfLargest[1]);
This stores the result in positionOfLargest and then prints out x/y coordinates the way you want them.
Hey for finding largest you can have your method like this.
public static int[] locateLargest(double[][] a)
{
int maxValue = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
If(a[i][j] > maxValue)
{
maxValue = a[i][j] ;
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
u should edit your locateLargest as this:
public static int[] locateLargest(double[][] a)
{
//may be ur array is contain negative
//so u can not use zero as MAX it's better to use first array element
int MAX = a[0][0];
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if(MAx < a[i][j]){
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
String result="location of largest num =a["+maxRow+"]["+maxColumn+"]";
return largest;
}

java 2D array search/sort/add

I have to take in a few ID numbers and how many boxes sold by the ID number...split those into two arrays...which I've done....then sort the array reporting the largest sale of boxes sold....the(and this is my problem) if the same id number is entered, add the number of boxes sold together and make it take up only one spot in the array
example....
idNum 1 = 100
idNum 3 = 500
idNum 1 = 200
so idNum 1 = 300
//declarations
int [][] stupidKids = new int[10][2];//10 rows....2 columns
int entry = 0;
int tempNum;
int tempTotal = 0;
int tempId;
int found = -1;
//user input section
for(int i = 0; i < 2; i++)
{
System.out.print("Please enter the class ID");
Scanner scan = new Scanner(System.in);
stupidKids[i][0] = scan.nextInt();
System.out.print("Please enter the amount of cookies sold");
stupidKids[i][1] = scan.nextInt();
System.out.println(stupidKids[i][0] + "Cookies " + stupidKids[i][1]);
}
//sorting process
for(int i = 0; i < 2; i++)
{
if(stupidKids[i][1] > stupidKids[i+1][1])
{
tempNum = stupidKids[i][1];
stupidKids[i][1] = stupidKids[i + 1][1];
stupidKids[i + 1][1] = tempNum;
tempId = stupidKids[i][0];
stupidKids[i][0] = stupidKids[i+1][0];
stupidKids[i+1][0] = tempId;
}
}
//comparing for same ID Num
for(int i = 0; i < 1; i++)
{
if(stupidKids[i][0] == stupidKids[i+1][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[i+1][1]);
}
}
System.out.println("Final num " + tempTotal);
You must loop through your for loops 10 times rather than just twice, this way you get through the whole array.
for(int i = 0; i < 10; i++)
Below is the code to compare the IDs against each other in the 2D array. Although I am not quite sure about why you would want it to take up only one space per ID as you will end up with a lot of NULL values in the array as you can not easily resize an array (to do this requires an implementation of a basic algorithm)
for(int i = 0; i < 10; i++)
{
tempID = stupidKids[i][0];
for(int j = 0; j < 10; j++)
{
if( i != j)
{
if(stupidKids[i][0] == stupidKids[j][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[j][1]);
}
}
}
}
System.out.println("Final num " + tempTotal);

Categories