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);
}
}
Related
I wanted to check if frequency of minimum element is odd: I would print lucky, otherwise print "Unlucky".
I used a technique related to counting sort arr[arr1[i]]++ counting duplicated as value and reference to the actual value to it's INDEX. I tried with this but it didn't bring the correct answer [appreciate if you correct my code rather than a new different solution]
input: 6 6 6 4 4 4 4 3 3 3 7 7
output: Unlucky
since the minimum frequency is 7, 7%2!=0 so Unlucky
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t=in.nextInt();
while(t-->0) { //Test cases
int n=in.nextInt();//array's length
int arr[]=new int[n];// array
for(int i=0;i<arr.length;i++) {
arr[i]=in.nextInt();
}
int counter[]=new int[256];//counting duplicates
for(int i=0;i<arr.length;i++) {
counter[arr[i]]++;
}
int min=1;
int pos=0;
for(int i=0;i<counter.length;i++) {
if(counter[i]<min && counter[i]!=0) { //search for minimal frequency (counter[i]!=0 since our counter array could easily have lot zeroes
min=counter[i];
pos=i;
}
}
System.out.println((pos%2==0)?"Unlucky":"Lucky");
}
}
There is no need to the while loop and other loop for counter, you assign the array using n variable,
then you enter values to the arr and check frequency in the same loop.
And select the min frequency to check if it's lucky or not
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();// array's length
int arr[] = new int[n];// array
int counter[] = new int[n];
int min = 1;
int pos = 0;
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
counter[arr[i]]++;
if (counter[i] < min && counter[i] != 0) {
min = counter[i];
pos = i;
}
}
System.out.println((pos % 2 == 0) ? "Unlucky" : "Lucky");
in.close();
}
, input
12 6 6 6 4 4 4 4 3 3 3 7 7
, output
Unlucky
Consider the following points:
Your program is less useful/efficient for three reasons: (A) It will work for integers from 0 to 255 only (B) You are using a fixed size array of size 256 which means that even if the user enters just a few numbers, it will consume space for 256 integers (C) You are iterating the loop 256 times to calculate the frequency even if the user enters just a few numbers.
There are so many ways to count the frequency of numbers. Commonly people use a Map to do so. I've used the same thing in the function, minFrequencyNumber shown below:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int n = in.nextInt();
int arr[] = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
System.out.println("The number with minimum frequency is: " + minFrequencyNumber(arr));
System.out.println((minFrequencyNumber(arr) % 2 == 0) ? "Unlucky" : "Lucky");
}
public static int minFrequencyNumber(int[] arr) {
Map<Integer, Integer> m = new HashMap<>();
// Iterate the array
for (int i : arr) {
// If the number does not exist in the Map, put the number as the key and 1 as
// the value (frequency); otherwise, put the number as the key in the map by
// increasing its value (frequency) by 1
m.put(i, m.getOrDefault(i, 0) + 1);
}
int num = 0, minFrequency = Integer.MAX_VALUE;
// Iterate the map
for (Entry<Integer, Integer> e : m.entrySet()) {
if (e.getValue() < minFrequency) {
minFrequency = e.getValue();
// Store the key (the number) whose frequency is minimum
num = e.getKey();
}
}
return num;
}
}
A sample run:
Enter the size of array: 12
Enter 12 integers: 6 6 6 4 4 4 4 3 3 3 7 7
The number with minimum frequency is: 7
Lucky
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);
}
}
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];
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
I tried to sort an array accending and count the array elements
please help me find whats missing, have debugged many times. here is my code and the output i got. Thanks
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[30];
int i, count=0;
System.out.println("Enter the integers between 1 and 100" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
if(num[i]==0)
break;
count++;
}
calling the function here
Sorting(num, i, count);
}
public static void Sorting(int[] sort, int a, int con){
if (a<0) return;
/*am sorting the array here*/
Arrays.sort(sort);
int j, count=0;
for(j=0; j<con; j++){
if(sort[a]==sort[j])
count++;
}
System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);
}
}
Here is the output:
run:
Enter the integers between 1 and 100
2
5
4
8
1
6
0
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
Your problem is that the array is of size 30 and when you sort it you have all the values you did not assign to equal to 0 and thus they go in the front of the sorted array. Later on out of the first 6 numbers all are 0 so the output you have is correct.
To aviod the problem you face I suggest you use ArrayList instead of simple array so that you can add elements dynamically to it.
Try this
The counting method
public int count(int[] values, int value)
{
int count = 0;
for (int current : values)
{
if (current == value)
count++;
}
return count;
}
Then use
int[] sorted = Arrays.sort(num);
for (int value : sorted)
{
System.out.println("" + value + " occurs " + count(sorted, value) + " times");
}
This works for sure.
You are doing a bit more work than is necessary. I would solve this like so:
Map<Integer, Integer> countMap = new HashMap<Integer,Integer>();
for( i=0; i<num.length; i++){
int current = input.nextInt();
if(countMap.get(current) != null)
{
int incrementMe = countMap.get(current);
countMap.put(current,++incrementMe);
}
else
{
countMap.put(input.nextInt(),1);
}
}