Finding out the frequency of unique numbers - java

I am trying to solve a problem in Java as part of my assignment. The problem is as below:
The user enters ten numbers one by one upon prompting by the screen. The screen then assigns all the distinct value to an array and a similar array to hold the frequency of how many times those numbers have appeared.
I have done the below work, but seems I am stuck somewhere in assigning the frequencies and distinct values to the arrays:
import java.util.*;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
for (int k=0;k<10;k++)
{
count[k]=0;
distinct[k]=0;
}
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter number 0: ");
numbers[0]=input.nextInt();
count[0]=1;
distinct[0]=numbers[0];
int j=0;
for (int i = 1;i<10;i++)
{
System.out.print("Enter number "+i+": ");
numbers[i]=input.nextInt();
while(j<i)
{
if (distinct[j]==numbers[i])
count[j]=count[j]+1;
else
distinct[j+1]=numbers[i];
j++;
}
}
for (int k=0;k<10;k++)
{
System.out.println(distinct[k]+ " "+count[k]);
}
}
}
I know that it is not fair to ask someone to help me solve the problem. But any kind of hint will be helpful.
Thank you

are the numbers limited to 0-9? If so, I would simple do the assignment.
(please note you will assign the input to a variable called "input"):
numbers[0]=input;
count[input]++;
Also you can start your for loop in "0" to avoid the assignment prior to the for loop.
Just a hint.
Hope this helps!

the ideal data structure would be a HashMap
Steps:
1) initialize an array to store the numbers and for each input
2) check if a hashmap entry with key as the entered number already exists
3) if exists simply increase its count
4) else create new entry with key as the number and count as 1
so at the end your frequencies would be calculated
if you are forced to use 2 arrays
1) initialize two arrays
2) for each input loop the number array and check whether that number is already in the array
3) if so take the array index and increment the value of the frequency array with the same index
4) if not freq[index] = 1

A proper way of doing that would be:
public Map<Integer, Integer> getFrequencies(Iterable<Integer> numbers) {
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(Integer number : numbers) {
if (frequencies.get(number) == null) {
frequencies.put(number, 0);
}
frequencies.put(number, frequencies.get(number) + 1);
}
return frequencies;
}
It returns a map number -> frequency.
Arrays are not a way to go in Java, they should be avoided whenever possible. See Effective Java, Item 25: Prefer lists to arrays.

I removed the Scanner object to write the code faster, just replace it with your code above and it should work.
int[] numbers = { 1, 2, 2, 2, 3, 3, 3, 1, 1, 2 };
int[] count = new int[10];
int[] distinct = new int[10];
count[0] = 1;
distinct[0] = numbers[0];
int disPos = 1; //Current possition in the distinct array
boolean valueInarray = false;
for (int i = 1; i < 10; i++) {
valueInarray = false;
for (int d = 0; d < i; d++) {
if (numbers[i] == distinct[d]) {
count[d] = count[d] + 1;
valueInarray = true;
break;
}
}
if (!valueInarray) {
distinct[disPos] = numbers[i];
count[disPos] = 1;
disPos++;
}
}

If you ABSOLUTELY HAVE TO use arrays.. here is a way to do it…
import java.util.Scanner;
import java.util.Arrays;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
int [] distinct1 = new int[1];
int distinctCount = 0;
boolean found = false;
Scanner input = new Scanner(System.in);
for (int i=0; i<10; i++) {
found = false;
System.out.print("Enter number " + i);
numbers[i]=input.nextInt(); //Add input to numbers array
for (int j=0; j<=distinctCount; j++)
{
if (distinct1[j] == numbers[i]){ // check to see if the number is already in the distinct array
count[j] = count[j] + 1; // Increase count by 1
found = true;
break;
}
}
if (!found) {
distinct[distinctCount] = numbers[i];
count[distinctCount] = 1;
distinctCount++;
distinct1 = Arrays.copyOf(distinct, distinctCount+1);
}
}
for (int j=0; j<distinctCount; j++)
System.out.println("The number " + distinct1[j] + " occurs " + count[j] + " times" );
}
}

I think this is what you need, correct me if I'm wrong...
import java.util.HashMap;
import java.util.Scanner;
public class JavaApplication10 {
public static void main(String[] args) {
// Initializing variables
int[] numbers = new int[10];
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
Scanner input = new Scanner(System.in);
// Getting the 10 inputs
for(int x=0; x<10; x++) {
// Asking for input
System.out.println("Enter number "+x+":");
numbers[x]=input.nextInt();
// If the table contains the number, add 1
// Otherwise: set value to 1
if(table.containsKey(numbers[x]))
table.put(numbers[x], table.get(numbers[x])+1);
else
table.put(numbers[x],1);
}
// Closing the reader
input.close();
// Get the highest and smallest number
int highest=0;
int smallest=0;
for(int i:table.keySet()) {
if(i>highest)
highest=i;
if(i<smallest)
smallest=i;
}
// For every value between the smallest and the highest
for (int x=smallest; x<=highest; x++) {
// Check if the frequency > 0, else continue
if(table.get(x)==null)
continue;
// Output
System.out.println(x+" is "+table.get(x)+" times in \'frequence\'");
}
}
}
This also handles with negative numbers, unlike the other's codes. If you don't want to use HashMaps let me know so I can create something with arrays.
Let me know if it (doesn't) works!
Happy coding (and good luck with your assignment) ;) -Charlie

Related

Java lottery program, having trouble comparing outputs

I have to do an 'instant lottery' program in my first computer science class. All semester my professor has read verbatim from the book, so now I am a little lost, truthfully. I know how to do most of it, but am just having trouble figuring out array sort and how to compare user input and the random number output. My professor refuses to answer questions about take home assignments and has banned the use of anything except: arrays, loops and math.random- so no sets or anything more complex that could help. I've seen other programs that compile, but all with sets.
I have the code for user input of the lottery numbers and to generate the output of the random numbers. I can most likely also figure out how to print the payout with if/else. I just need to know how to get the program to compare the numbers an figure out if the user is a "winner" or not.
import java.util.Scanner;
public class TheLottery {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); //user input of their lottery numbers
System.out.print("Enter number 1: ");
int num1 = keyboard.nextInt();
System.out.print("Enter number 2: ");
int num2 = keyboard.nextInt();
System.out.print("Enter number 3: ");
int num3 = keyboard.nextInt();
System.out.print("Enter number 4: ");
int num4 = keyboard.nextInt();
System.out.print("Enter number 5: ");
int num5 = keyboard.nextInt();
System.out.print("Enter number 6: ");
int num6 = keyboard.nextInt();
}
int[] lottery = new int[6];
int randomNum;
{
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " "); //print random numbers
}
}
the final program should have the user enter 6 numbers, the program compare the numbers for matches, figure out if the user is a 'winner', show the prize and an added thing is show how much they spent (each 'ticket' is $1) vs how much they won. So far all that outputs is the scanner and random numbers
It looks like you obtained six numbers then didn't use them. Your lottery array is automatically initialized to zero. I think you're trying to compare an array with inputs to a random array, so you need a loop to put your entered values into. After you do that, initialize your random array, then just compare the arrays.
public static void main(System[] args) {
Scanner in = new Scanner(System.in);
int[] lottery = new int[6];
System.out.println("Enter " + lottery.length + " numbers: ");
for (int i = 0; i < lottery.length; i++) {
lottery[i] = in.nextInt();
}
The specific question has to do with how to do the comparison and figuring a "winner". It isn't clear what makes the definition of "winner".
Based upon my comment, and as shown in the answer by #szoore, I would use an array to collect the input. I'd use a method to collect (since one can change to use a different method for the selections, which makes testing easier).
/**
* Obtain the specified number of entries from the user
*/
public static int[] getUserSelections(final int numSelections)
{
Scanner in = new Scanner(System.in);
// read N entries from the user
int[] nums = new int[numSelections];
// NOTE: no error processing in this loop; should be refined
// bad numbers (e.g., negative, too large), duplicate entries, etc.
// need to be removed
for (int i = 0; i < numSelections; ++i) {
System.out.print("Enter number " + (i + 1) + ": ");
nums[i] = in.nextInt();
}
return nums;
}
The OP has a basic generation for the lottery numbers, but again I'd use a method. This has a slight refinement to the duplicate check, by using a method, and also allows the same duplicate check method to be later used for checking matches:
public static int[] getLotteryNumbers(final int numSelections)
{
// the largest number to be selected; all numbers between
// 1 and maxNum (inclusive) will have equal(-ish) probability
// of being generated
final int maxNum = 50;
int[] lottery = new int[numSelections];
Random rnd = new Random();
// make N random selections, and ensure we don't have duplicates
for (int i = 0; i < numSelections; ++i) {
boolean generate = true;
while (generate) {
int sel = rnd.nextInt(maxNum) + 1;
generate = numberInArray(sel, lottery);
if (! generate) {
lottery[i] = sel;
}
}
}
return lottery;
}
/**
* Returns true if the specific queryNum is found in the pastSelections
* Could be slightly optimized by passing how many selections have
* already been made
*/
public static boolean numberInArray(int queryNum, int[] pastSelections)
{
// look at each element and see if already there; exit via return
// if so
for (int i = 0; i < pastSelections.length; ++i) {
if (pastSelections[i] == queryNum) {
return true;
}
}
return false;
}
The use of the method 'numberInArray' then allows for fairly easy check on how many numbers match:
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
Determining payouts, etc. is straight forwarding using if/else or (perhaps better) a switch based on the number of matches.
Also, the entries and lottery selections should probably be sorted. It isn't clear if the built-in sort may be used or not. Write the sort method as appropriate:
/**
* Sorts the array; implement sorting as needed
*/
public static void sort(int[] arr)
{
Arrays.sort(arr);
}
/*
* outputs the array if one cannot use Arrays.toString(arr)
*/
public static void outputArray(int[] arr)
{
for (int i = 0; i < arr.length; ++i) {
System.out.printf("%2d ", arr[i]);
}
System.out.println();
}
Sample main:
public static void main(String[] args)
{
// how many options for the lottery; here it is 6
final int numEntries = 6;
// this method obtains from user
int[] userEntries;
userEntries = getUserSelections(numEntries);
sort(userEntries);
// display User selections
outputArray(userEntries);
int[] lottery = getLotteryNumbers(numEntries);
sort(lottery);
// display lottery numbers
outputArray(lottery);
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
//
// TODO: calculate winnings based upon the number of matches
//
}

Java Random Utility Generating Too Many 0's And Static Numbers

The line birthdays[j] = rnd.nextInt(365); seems to generate extra 0's in the int[] birthdays array. It also seems to add an EXTRA 0 into the array and generate static values depending on how many simulations I run and how many birthdays I generate. For instance, if I do 5 simulations and enter a 3 for the number of people in each simulation's "birthday pool" I always get an array of [0, 0, 289, 362].
Any help understanding the problem would be greatly appreciated.
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn);
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// Prompt user to provide the number of simulations and number of people and return them as an array
public static int[] promptAndRead(Scanner stdIn) {
int numberOfSimulations = 0;
while(numberOfSimulations < 1 || numberOfSimulations > 50000) {
System.out.println("Please Enter the number of simulations to do. (1 - 50000) ");
numberOfSimulations = stdIn.nextInt();
}
int sizeOfGroup = 0;
while(sizeOfGroup < 2 || sizeOfGroup > 365) {
System.out.println("Please Enter the size of the group of people. (2 - 365) ");
sizeOfGroup = stdIn.nextInt();
}
int[] simulationVariables = {numberOfSimulations, sizeOfGroup};
return simulationVariables;
}
// This is the method that actually does the calculations.
public static double compute(int numOfSims, int numOfPeeps) {
double numberOfSims = 0.0;
double simsWithCollisions = 0.0;
int matchingBirthdays = 0;
int[] birthdays = new int[numOfPeeps + 1];
int randomSeed = 0;
for(int i = 0; i < numOfSims; i++)
{
randomSeed++;
Random rnd = new Random(randomSeed);
birthdays = new int[numOfPeeps + 1];
matchingBirthdays = 0;
for(int j = 0; j < numOfPeeps; j++) {
birthdays[j] = rnd.nextInt(365);
Arrays.sort(birthdays);
}
for(int k = 0; k < numOfPeeps; k++) {
if(birthdays[k] == birthdays[k+1]) {
matchingBirthdays++;
}
}
if(matchingBirthdays > 0) {
simsWithCollisions = simsWithCollisions + 1;
}
}
numberOfSims = numOfSims;
double chance = (simsWithCollisions / numberOfSims);
return chance;
}
}
The line "birthdays[j] = rnd.nextInt(365);" seems to generate extra 0's in the int[] birthdays array.
Well, it doesn't. The array elements where zero to start with.
What that statement actually does is to generate a single random number (from 0 to 364) and assign it to one element of the array; i.e. the jth element. That is not what is required for your problem.
Now, we could fix your code for you, but that defeats the purpose of your homework. Instead I will give you a HINT:
The birthdays array is supposed to contain a COUNT of the number of people with a birthday on each day of the year. You have to COUNT them. One at a time.
Think about it ...
int arrays are by default initialized to 0 unless explicitly specified. Please see this Oracle tutorial about Arrays.
I found the problem myself. The issue was that having the "Arrays.sort(birthdays);" statement inside of a loop. That generated extra 0's.

Frequency of elements in an array [duplicate]

This question already has an answer here:
java: Find integer's frequency in an array
(1 answer)
Closed 6 years ago.
I am relatively new to programming and i have been working on a java project for about 2 days that reads ten numbers and displays the frequency of occurrence of each number , while my code looks good and it run ,it doesnt seem to be able to count two numbers that are far apart even after sorting ,please i have run out of ideas and am open to suggestions
Here's my code:
public static void sortarray(int [] tennumbersarray ){
for(int i =0 ;i<9;i++){
int currentmin = tennumbersarray[i];
int currentminindex = i;
for(int j=i+1;j<10;j++){
if(currentmin>tennumbersarray[j]){
currentmin= tennumbersarray[j];
currentminindex = j;
}
}
if(currentminindex!=i){
tennumbersarray[currentminindex]=tennumbersarray[i];
tennumbersarray[i]=currentmin;
}
}
}
public static void main(String[] args) {
int tennumbersarray [] = new int[10];
for (int i =0 ;i<10;i++){
String tennumbersstring = JOptionPane.showInputDialog("enter a number :");
tennumbersarray [i] = Integer.parseInt(tennumbersstring);
}
sortarray ( tennumbersarray);
for (int i=0;i<10;i++){
int count =1;
for (int j=i+1;j<10;j++)
{
if(tennumbersarray[i]==tennumbersarray[j])
{
count++;
}
else{
break;
}
}
String output = ""+tennumbersarray[i] +"----> "+count;
JOptionPane.showMessageDialog (null,output);
i+=count;
}
}
}
I think using HashMap you can easily find the frequency of the number.
Ex:
int tenNumbersArray[] = new int[10];
tenNumbersArray[0] = 10;
tenNumbersArray[1] = 20;
tenNumbersArray[2] = 30;
tenNumbersArray[3] = 10;
tenNumbersArray[4] = 10;
tenNumbersArray[5] = 40;
tenNumbersArray[6] = 50;
tenNumbersArray[7] = 60;
tenNumbersArray[8] = 70;
tenNumbersArray[9] = 70;
HashMap<Integer, Integer> numberAndItsOcuurenceMap = new HashMap<Integer, Integer>();
for (int num : tenNumbersArray) {
Integer frequency = numberAndItsOcuurenceMap.get(num);
numberAndItsOcuurenceMap.put(num, frequency != null ? frequency + 1 : 1);
}
OUTPUT:
{50=1, 70=2, 20=1, 40=1, 10=3, 60=1, 30=1}
To get the frequency of the particular just pass the key to the map.
Ex:
numberAndItsOcuurenceMap.get(10);
OUTPUT
3
You can use a Map
public static void main(String[] args) {
int tennumbersarray[] = new int[10];
for (int i = 0; i < 10; i++) {
String tennumbersstring = JOptionPane.showInputDialog("enter a number :");
tennumbersarray[i] = Integer.parseInt(tennumbersstring);
}
Map<Integer, Integer> frequences = new HashMap<Integer, Integer>();
for(int number : tennumbersarray)
if(frequences.get(number) == null)
frequences.put(number, 1);
else
frequences.put(number, frequences.get(number) + 1);
for(Entry<Integer, Integer> entry : frequences.entrySet())
JOptionPane.showMessageDialog(null, entry.getKey() + "----> " + entry.getValue());
}
Resorting to sorting the array in order to count the frequency of its items is an idea that works, but it is not necessary. For instance, I'd use that approach if I were told that there was a file (on a Unix computer) with thousands of numbers and I was asked to count the number of times each number appears in that file without writing any Java code:
cat file | sort -n | uniq -c
But since you are tasked with writing one of your first Java programs, I introduce you to the idea of a hash table. Such a hash table, in Java, is realized using a HashMap, where keys are integers and values are also integers (for starters). Every time you encounter an integer, you increment its count:
public static Map<Integer, Long> count(int[] ints) {
Map<Integer, Integer> counter = new HashMap<>();
for (int i : ints) {
if (counter.containsKey(i))
counter.put(i, counter.get(i) + 1);
else
counter.put(i, 1); // initialize
}
return counter; // here, we'll have each number mapped to
// how many times it appears in ints {1: 23, 3: 2} ...
}
try this code instead:
public int[] frequency(int[] tennumbers){
int[] frequency = new int[100];
for(int i=0; i< tennumbers.length ; i++){
frequency[tennumbers[i]]++;
}
return frequency;
}
That way you can know the frequency of, for example '60' by accessing the 60th index of your frequency array. like this:
int[] freq=frequency(tennumbers);
int sixtyFrequency=frequ[60];

How do I count the number of items an Integer occur in an ArrayList?

My idea is to build a list having the user writing in 5 different ints (doesnt have to be even numbers) and then write a number to see how many time that number occurs in the list. How do I do this? This is my example code im having problems with:
package Listor;
import java.util.ArrayList;
import java.util.Scanner;
public class Tal {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
ArrayList<Integer> evenNumbersList = new ArrayList<>();
System.out.print("Write 5 even numbers: ");
int evenNumber = 0;
for (int i = 0; i < 5; i++) {
evenNumber = s.nextInt();
evenNumbersList.add(evenNumber);
}
System.out.println(evenNumbersList);
System.out.println("Write a number and see how many times it occurs: ");
int intHappens = s.nextInt();
int sum = 0;
for (int i = 1; i < evenNumbersList.size(); i++) {
if (i == intHappens) {
sum += 1;
}
}
System.out.println(sum);
}
}
Two errors I see:
1) Your for loop needs to start from 0, not 1.
2) Your if statement should be if (evenNumbersList.get(i) == intHappens).
You probably want to iterate over the evenNumberList list and compare the values in the list with intHappens. Use a for(Variabletype varname : List list) for-loop. Read up on Enhanced For-Loops

How do I reverse the integers in one array using another array?

I have gotten 10 values from the user, and I am suppose to put that into an array and call it into a method, and then call another method which contains an array that reverses the integers of the first array without using global variables. For example, the user gives me values 1,2,3, etc.. and I store that in the first array, then in the second array I output 3,2,1.
I have part of the code that gets the integers from the user, but I don't know how to reverse the array without using global variables. The code doesn't run when it gets to the second method at values[i];
Here is what I have so far:
public static void main(String[] args) {
getInput();
reverseInput();
System.exit(0);
}
public static void getInput() {
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers.");
for (int i = 0; i<values.length; i++) {//for loop to display the values entered
values[i] = keyboard.nextInt();
System.out.println("Value" + (i +1) + " is " + values[i]);
}
}
public static void reverseInput() {
System.out.println("Now we are going to reverse the numbers.");
Scanner keyboard = new Scanner(System.in);
int [] values;
values = new int[10];
for (int i = (values.length -1); i>= 0; i--) {//for loop to display integers in reversed order
values[i];
System.out.println(values[i]);
}
}
First, if you are not going to be using global variables, then you will need to pass the array from the get input method to the reverseInput method. Something like this:
int[] values = getInput();
reverseInput(values);
Then to output the array in your reverseInput method, it would have to look like this:
public static void reverseInput(int[] values) {
for(int i = (values.length - 1); i >= 0; i--){
System.out.println(values[i]);
}
}
You can use the ArrayUtils.reverse from Commons Lang:
ArrayUtils.reverse(values);
Ok, you understand how to display the elements in reference order. As you wrote:
for (int i = (values.length - 1); i >= 0; i--) {
System.out.println(values[i]);
}
So given that, how would you put the elements of values (say it has 5 elements) in another array (call it reversedValues) such that values[4] was put into reversedValues[0] and so on up to values[0] being put into reversedValues[4]?
use the "getInput" as basis to get the 10 numbers, then after the "for" loop, just do another for loop in reverse
public static void reverseInput()
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers, we are going to reverse the numbers");
for (int i = 0; i<values.length; i++) //for loop to display the values entered
{
values[i] = keyboard.nextInt();
};
int[] revValues;
revValues = new int[10];
for (int i = (values.length -1); i>= 0; i--) //for loop to display integers in reversed order
{
revValues[ revValues.length -1 -i ] = values[ i ];
System.out.println( revValues[ i ] );
}
}

Categories

Resources