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];
Related
public static void checkMultiple(int a[]){
//will use this count variable later
//int[] count = new int[10];
//first scan over the array
for (int i = 0; i < a.length; i++)
{
//seeded loop to check against 1st loop
for (int j = 0; j < i; j++)
{
if (a[i] == a[j])
{
System.out.print(a[i] + " ");
}
}
}
}
I'm having trouble counting repeated numbers in an integer array of 10 random numbers. I havent wrote the "count" function yet but the checkMultiple() will print out the numbers that are repeated. However, some of the time it prints correctly such as:
4 2 9 0 9 6 3 3 7 5
9 3
the first line being the whole array and the second the numbers that are repeated at least once in the array. But when there is more than two of a single integer, it counts every single one of that integer such as:
9 5 2 8 5 5 7 6 3 3
5 5 5 3
Any tips or advice would be much appreciated!
It looks like as you are looping through and then immediately outputting the results.
This prevents the program from comparing what's being currently parsed and what has already been been parsed and counted.
I would pass an empty array into the first FOR loop and instead of "System.out.print," store the number in the passed-in array. You can then compare the values that have already been parsed against the value currently being parsed to see if it has already been counted.
When the outside FOR loop exits, output the array that was originally passed in empty (and now has a record of every duplicate in the initial array)
You are counting the number of duplicate instances. Your second example has three pairs of duplicate 5's. That's why you see the 5 repeated three times. Only output unique duplicate results.
Just use a hash map, if the key does not exist add it to the map with the value 1, if it does increase the value, then print the hash map.
A single iteration of the array will solve the problem.
Map<Integer, Integer> counter = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if (counter.containsKey(a[i])) {
counter.put(a[i], counter.get(a[i]) + 1);
} else {
counter.put(a[i], 1);
}
}
Iterator it = counter.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
for (int i = 0; i < pair.getValue(); ++i) {
System.out.print(pair.getKey() + " ");
}
// or you could just print the number and how many times it was found
System.out.println(pair.getKey() + " " + pair.getValue());
it.remove();
}
try this
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class BirthdayCake {
private static void printcake(int n,int[] arr){
//Map<Integer,Integer> ha = new HashMap<Integer,Integer>();
int temp = arr[0],max=0, count=0;
/*for(int i=1;i<n;i++){
max = arr[i];
if(max<=temp){
temp=max;
count++;
break;
}
else{
max = arr[i];
count++;
break;
}
}*/
Arrays.sort(arr);
for(int i:arr){
System.out.println(i);
}
System.out.println("max:" +max);
max = arr[arr.length-1];
for(int i=0;i<n;i++){
if(arr[i]==max){
count++;
}
}
System.out.println("count:" +count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Entere thye array size:");
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
printcake(n,arr);
}
}
I'm supposed to create a mainmethod that calculates how many times a number have occured in a row. The user is supposed to input the numbers.
I guess I have to loop through an array though I'm not sure how..
Userinput to array, loop through and check if the number is the previous one.
Example:
1 3 4 5 6 6 6 9 - Output: The number 6 occured 3 times in a row
This is the code I have right now(sry missed to paste it):
public static void main(String[] args)
{
Scanner inp = new Scanner(System.in);
int counter = 0;
int[] x = new int[inp.nextInt()];
for (int i = 0; i < x.length; i++)
{
if(i == x[i])
{
counter++;
}
else
{
continue;
}
}
System.out.print(counter);
}
Any ideas?
Use a HashMap<Integer, Long> to track the number of occurences for each number:
Map<Integer, Long> numberOccurences = new HashMap<>();
for(int n : numbers) {
Long occurences = numberOccurences.get(n);
if(occurrences == null) { // first time the number n is seen
numberOccurences.put(n, 1L);
} else {
numberOccurences.put(n, occurences + 1);
}
}
I have tried the below program and i am stuck please assist me.Below is my program
import java.util.ArrayList;
public class PrintNosandRepetition
{
public static void main(String[] args)
{
int a[] = new int[] {1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};
for (int i=0; i< a.length; i++){
System.out.print(a[i]+ " ");
}
for (i=1, j<a.length; j++)
}
The output has to be is the fashion "1- repeated 3 times".etc
You can sort the original array and then loop through it to scan the elements one by one. This will run in O(nlogn).
Or you can use a Map<Integer, Integer> which will store for each number it's number of occurences. This solutions runs in O(n) but uses extra memory.
int a[] = new int[] {1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};
HashMap occurrenceMap = new HashMap()<Integer, Integer>;
int number;
Integer occurrences; //accepts null
for (int i=0; i<a.length; i++){
number = a[i];
occurrences = occurrenceMap.get(number);
if (occurrences == null) { //had no occurrences until this point
occurrenceMap.put(number, 1);
}
else {
occurrenceMap.put(number, occurrences+1);
}
}
//iterate over your map and print the pairs
Can't test it right now so I apologize for any eventual syntax errors.
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
Like my question, i need to generate random numbers that have identical pairs between a range. i have tried to generate random numbers and stored in an array but the numbers are repeating more than twice. i have 16 random numbers to be generated in the range. Any idea how to make it generate only identical pairs random number?
The following will do the job I think :
import java.util.*;
class Randoms {
public static void main(String[] args) {
List<Integer> randoms = new ArrayList<Integer>();
Random randomizer = new Random();
for(int i = 0; i < 8; ) {
int r = randomizer.nextInt(8) + 1;
if(!randoms.contains(r)) {
randoms.add(r);
++i;
}
}
List<Integer> clonedList = new ArrayList<Integer>();
clonedList.addAll(randoms);
Collections.shuffle(clonedList);
int[][] cards = new int[8][];
for(int i = 0; i < 8; ++i) {
cards[i] = new int[]{ randoms.get(i), clonedList.get(i) };
}
for(int i = 0; i < 8; ++i) {
System.out.println(cards[i][0] + " " + cards[i][1]);
}
}
}
One sample run of the above gives :
1 2
8 6
4 3
3 7
2 8
6 1
5 5
7 4
Hope that helps.
Generally, if you put the numbers you wish to generate in an array (in your case, an array of length 16 with two each of 1, 2, ..., 8), then randomly permute the array, you will get what you want. You can randomly permute the array using code here.
I believe this clearly shows you how to approach the problem:
public static List<Integer> shuffled8() {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 8; i++) {
list.add(i);
}
Collections.shuffle(list);
return list;
}
public static void main(String[] args) {
List<Integer> first = shuffled8();
List<Integer> second= shuffled8();
for (int i = 0; i < 8; i++) {
System.out.println(first.get(i) + " " + second.get(i));
}
}
shuffled8 simply returns a list of numbers 1 to 8 shuffled. Since you need two of such lists, you invoke it twice, and store it in first and second. You then pair first.get(i) with second.get(i) to get the properties that you want.
To generalize this, if you need triplets, then you just add List<Integer> third = shuffled8();, and then first.get(i), second.get(i), third.get(i) is a triplet that has the properties that you want.
I have made this way :
Random random = new Random();
List<Integer> listaCartoes = new ArrayList<Integer>();
for(int i=0; i<8;)
{
int r = random.nextInt(8) + 1;
if(!listaCartoes.contains(r))
{
listaCartoes.add(r);
listaCartoes.add(r);
++i;
}
}
Collections.shuffle(listaCartoes);
Hope it helps ^_^