Finding the 10 highest frequencies in a randomized array-Java - 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;
}

Related

Why doesn't this program output one integer at the end of the loop?

So a jist of what the program needs to do is to count how many integers are greater than the average of the sum of all elements in an array. It does this as the last number it counts is the total number of integers greater than average. However, it also shows the number of times it has looped. For example, if the number of integers is supposed to be 3, it will show, 1,2,3. That's fine but the 1,2, the part is not necessary, just the 3. This is the only way I have found possible but is there a better way?
import java.util.Scanner;
public class Sparky
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int sum =0;
int n;
do
{
System.out.print("Enter integer n, greater than 0: ");
n = kbd.nextInt();
}while(n < 1);
System.out.println();
int[] arr = new int[n];
System.out.println("Array on one line: ");
for(int i = 0; i < arr.length; i++)
{
arr[i] = (int) (Math.random() * 500) + 1;
System.out.print(arr[i] + " ");
}
int max = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
System.out.println();
{
double x = 0;
double y;
for(int i = 0; i < arr.length; i ++){
x = arr[i] + x;
}
y = x / arr.length;
System.out.println("Average: " + y);
System.out.println("Number of integers greater than average: ");
int count = 1;
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
System.out.print(count + ",");
count ++;
}
}
}
}
}
Change the last section of your code from this :
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
System.out.print(count + ",");
count ++;
}
}
To this :
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
count ++;
}
}
System.out.print(count);
It should print the number of integers greater than average.
Xerox's answer was good, but I noticed a bug in your code. If you start count at 1, your count will be off. Also, I thought I'd show you how to use a foreach loop. So I made some updates to your code, ran it, and added comments for you. Remember, short variable names were used in the 80s because they took up disk space and slowed down processing time when they were larger. That's no longer an issue, and if your variable names are cryptic, your code is difficult to read, even when it's simple. You'll notice that your code is much easier to read with descriptive variable names and a foreach loop. I left the rest of the file for you to do if you are interested.
import java.util.Scanner;
public class Sparky {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n;
do {
System.out.print("Enter integer n, greater than 0: ");
n = kbd.nextInt();
} while (n < 1);
System.out.println();
int[] arr = new int[n];
System.out.println("Array on one line: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 500) + 1;
System.out.print(arr[i] + " ");
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println();
{
double x = 0;
double average; //Better to have readable variables. "y" means nothing, "average" is clear, especially in the next section.
for (int i = 0; i < arr.length; i++) {
x = arr[i] + x;
}
average = x / arr.length;
System.out.println("Average: " + average);
int numberGreaterThanAverage = 0; //This needs to start at 0 or your count will be off. Also, name the variable what it does. Short variable names help no one.
for (int number: arr) { //This is called a foreach loop. It does the same thing as your loop, but is much each to read, also I renamed "i", short for "iterator" to "number" which is what it actually is, a number in the array.
if (number > average) {
numberGreaterThanAverage++;
}
}
System.out.println("Number of integers greater than average: " + numberGreaterThanAverage); //This needed to be moved out of the loop, and it also could be concatenated with the rest of the text to put it all on one line.
}
kbd.close(); //You need to close this or you can get a memory leak
}
}
Always consider printing statements after you are done with modifying the values, best is to print outside the loop.
In this case, Count is being printed before it is incremented, on the last iteration of the loop, it increments and quits the loop.
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
// System.out.print(count + ","); count is being printed before it is incremented
count ++;
}
}
System.out.print(count + ","); //Should be printed **after** the loop ends.

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 does this code that fills an array with 10 distinct random numbers work?

Can someone please explain the thought process behind this code? I am kind of confused on how it works. This is the question that the code is addressing:
Write code (using one or more loops) to fill an array "a" with 10 different random numbers between 1 and 10.
Thank you so much for any help!
public static void main(String[] args){
//R8.8
int a[] = new int[10];
Random randomGenerator = new Random();
for (int i = 0; i < a.length; i++){
a[i] = 1 + randomGenerator.nextInt(100);
}
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
See my comments in the code itself:
public static void main(String[] args){
//make a new array of 10 integers
int a[] = new int[10];
//declare an object which we can use to generate random numbers
//this object probably uses the system time to generate numbers that appear random
//but at the end of the day, java does it for us so
//we don't really need to know or care how it generates random numbers
Random randomGenerator = new Random();
//loop over each element in our array
for (int i = 0; i < a.length; i++){
//for each element, set that element to a random between 1 and 100 inclusive
//nextInt(x) gets a number between 0 (inclusive) and x (not inclusive)
//so to translate that to 1 to x inclusive, we need to add 1 to the result
a[i] = 1 + randomGenerator.nextInt(100);
}
//everything below here does literally nothing to solve the problem
//everything you need to fill the array with random numbers is above
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
Please note that you should use 1 + randomGenerator.nextInt(10); to fill the array with numbers between 1 and 10, not 1 + randomGenerator.nextInt(100);.

explaining this simple program - bucket sort

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]++;

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;
}

Categories