Java count occurrences in array - java

I am trying to count the number of occurrences in an array of integers and return the amount of times each number was displayed. My code counts the right amount of occurrences, but it displays them more than once.
Here is the relevant code:
int num = input.nextInt();
int count = 0;
int[] integers = new int[num];
for(int i = 0; i < num; i++) {
System.out.print("Enter int 1-50: ");
integers[i] = input.nextInt();
}
for(int i = 0; i < num; i++) {
for(int j = 0; j < num; j++) {
if(integers[i] == integers[j]) {
count++;
}
}
System.out.println(integers[i] + " occurs "+count+" times.");
count = 0;
}
The issue is that if a number occurs more than once, it displays that number more than once. For example, {1, 2, 2, 3} would print "2 occurs 2 times" twice. I understand why this happens but I'm wondering if there's a simple way to make sure these statements only print once.

Your problem is the print statement. You call print at every iteration. Instead, you can store that count value in a map:
1 -> 1
2 -> 2
3 -> 1
Where the key is the integer value you are counting, and the value is how many times it appears in the array. At the end you can just print the map:
for(int key : map.keySet()) {
int value = map.get(key);
System.out.println(key + " occurs "+value+" times.");
}
You can find a more elegant solution here [link]

Without using Map :
If you input numbers will be within 1-50
then my approach will work
int a[]=new int[51];
int b[]={4,7,8,5,4,50,5,5,4,44};
for(int c:b){
a[c]++;
}
for(int c:b){
if(a[c]!=-1){
System.out.println("value: "+c+" "+"count"+ a[c]);
}
a[c]=-1;
}

Related

Trying to count repeated items in an integer Array but getting weird results

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

Counting integers in an array; How to eliminate duplicate output strings

I am writing a program that outputs how many times each integer is found in an array of integers. I have accomplished this, however, i have duplicate output strings.
This is the output:
>run:
>Please enter integers from 0 to 100:
1
2
3
4
4
5
0
// 1 occurs 1 time //
2 occurs 1 time //
3 occurs 1 time //
4 occurs 2 times //
4 occurs 2 times //
5 occurs 1 time //
BUILD SUCCESSFUL (total time: 14 seconds)
So as you can see, "4 occurs 2 times" prints twice since it is found twice in the array.
I just need some direction on how to eliminate the duplicates. Anything would be greatly appreciated.
import java.util.*;
public class WorkSpace3 {
public static void main(String[] args) {
int i = 0;
int count = 0;
int key = 0;
System.out.print("Please enter integers from 0 to 100: ");
int[] myList = new int[100];
Scanner s = new Scanner(System.in);
for (i = 0; i < myList.length; i++)
{
myList[i] = s.nextInt();
if (myList[i] == 0)
break;
}
while (key < myList.length && myList[key] != 0) {
for (i = 0; i < myList.length; i++)
{
{ if (myList[i] == myList[key])
{ count++; } }
}
if (count == 1)
System.out.println(myList[key] + " occurs " + count + " time ");
if (count > 1)
System.out.println(myList[key] + " occurs " + count + " times ");
key++;
count = 0;
}
}
}
A simple approach that is available to you is to mark the elements that you have counted with zeros. This approach is not universal; it is valid only because you use zero to mark the end of the input sequence by end-user.
You would have to slightly modify your code to use this approach: rather than looking for zero in the while loop, set up a variable to mark the length of the sequence. Set it to myList.length at the beginning, and then reset to i at the break. Now you can walk the list up to this max count, do the counting, and then set zeros into elements that you have already counted.
See the set element:
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Making a set element from array You remove the duplicates.
try this using Map
Map<Integer,Integer> counts=new HashMap<Integer,Integer>();
for (i = 0; i < myList.length; i++) {
if(counts.contains(myList[i]){
counts.put(myList[i],++counts.get(myList[i]);
}else{
counts.put(myList[i],1);
}

Negative Arrays and Error Messages

//MY TASK IS TWO MERGE TO ARRAYS INTO ASCENDING ORDER.Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int one[]= new int[10000];
int two[]= new int[10000];
int lengthShort=0;
int lengthLong=0;
int a =0;
int b =0;
System.out.println("Enter the values for the first array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<one.length && scan.hasNext(); i++){
one[i] = scan.nextInt();
a++;
if(one[i]<0){
one[i]=0;
break;
}
}
int length1 = a-1;
System.out.println("Enter the values for the second array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<two.length && scan.hasNext(); i++){
two[i] = scan.nextInt();
b++;
if(two[i]<0){
two[i]=0;
break;
}
}
int lengthTwo = b-1;
int mergeOne[] = new int[length1];
for (int i = 0; i<mergeOne.length; i++){
mergeOne[i]=one[i];
}
int mergeTwo[] = new int[lengthTwo];
for (int i = 0; i<mergeTwo.length; i++){
mergeTwo[i]=two[i];
}
System.out.println("First Array:");
for(int i=0; i<mergeOne.length; i++){
System.out.print(mergeOne[i] + " ");
}
System.out.println("\nSecond Array:");
for(int i=0; i<mergeTwo.length; i++){
System.out.print(mergeTwo[i] + " ");
}
if(mergeOne.length<=mergeTwo.length){
lengthLong = mergeTwo.length;
lengthShort = mergeOne.length;
}
else if(mergeOne.length>=mergeTwo.length){
lengthShort = mergeTwo.length;
lengthLong = mergeOne.length;
}
int merged[] = new int[length1 + lengthTwo];
for(int i = 0; i<lengthShort; i++){
if(i==0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i] = mergeOne[i];
merged[i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i] = mergeTwo[i];
merged[i+1]= mergeOne[i];
}
}
else if(i>0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i+i] = mergeOne[i];
merged[i+i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i+i] = mergeTwo[i];
merged[i+i+1]= mergeOne[i];
}
}
}
if(mergeOne.length<mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeTwo[k];
}
}
if(mergeOne.length>mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeOne[k];
}
}
for(int i = 0; i<merged.length; i++){
if((i+1)==merged.length)
break;
if(merged[i]>merged[i+1]){
int temp = merged[i+1];
merged[i+1]=merged[i];
merged[i]= temp;
}
}
System.out.println("\nMerged array in order is: ");
for(int i = 0; i<merged.length; i++){
System.out.print(merged[i] + " ");
}
}
}
//My code compiles in drjava but I have two issues:
1) It doesn't order the numbers in ascending order
2) When I run it through the site I have to submit this on it gives me the message as follows:
Runtime Error
Exception in thread "main" java.lang.NegativeArraySizeException
at Main.main(Main.java:281)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
You'll need to rethink your merge algorithm. Suppose you input arrays are
1 5 10 50 100 500
2 4 6 8 10 12 14 16
You'll need to repeatedly decide which element is smaller to put into the output. So after selecting N elements, your output will look like
1 2 4 5 6 8 10 10 12 14
And you will need to have indexes pointing at the place in the input arrays you'll need to look at next:
1 5 10 50 100 500
^^
2 4 6 8 10 12 14 16
^^
As you can see, the indexes could be at very different places in the input arrays. However, your code does a lot of this:
if(mergeOne[i]<=mergeTwo[i]){
which means it's only comparing elements from the input that are in the same location. This doesn't work, and trying to swap elements in the output after the fact isn't good enough to get the job done.
Basically, instead of having one index and comparing the elements of the two input arrays at the same index, you'll need two indexes. I'll let you take it from there, but I think you can figure it out.
(And I have no idea why you're getting NegativeArraySizeException.)

Loop Counting in Java

What I have is a program that prints out 4000+ random digits in the range of 1 to 99999. After printing, it shows the range, and a couple of other things, and then asks user for 5 numbers to be input and tells how many times it had to run the loop, but I'm getting an exception in main upon print, it's coming from the main for loop. Screenshot is attached. Desired should look something like:
(Randomly generated numbers):
25
192
33
(User Enters) Please enter number: 33
(System Response) It took 3 times to find the number.
If the number is not listed, as it is over 4000 integers, it will say, not found.
Here is code and screenshot:
Screenshot
Exception in Main java.lang.ArrayIndexOutOfBoundsException:0
Thank You!
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] input = new int[0];
int[] arrayone = new int[4096];
int loop = 0;
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
for(int in = 0; in<input.length; in++) {
if (arrayone[i] == input[in]) {
loop++;
}
}
}
for (int i = 0; i < 5; i++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[0] = s.nextInt();
if (min <= input[0] && input[0] <= max) {
System.out.println("It took " + loop + " time(s) to find the number " + input);
}
}
}
The problem with your input array is that you initialize it with a size of 0, so when you try to access the first location [0], you run out of the bounds since your array has a size of 0. In your answer you were also trying to determine the loops before asking the question. While doing this you were also trying go past the bounds of your input array with a size 0. What you should do is initialize your array of numbers first then for each guess loop through and determine if it's within the bounds of your max and min. Also note that just because the numbers are within the max and min doesn't guarantee the number is contained in the array because the numbers are not going to be sequential from max to min. You should check where you end up after your for-loop check for the input.
public static void main(String random[])
{
Scanner s = new Scanner(System.in);
int input = new int[5];
int[] arrayone = new int[4096];
int loop = 0;
//don't do anything here except fill the array with values
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
}
//ask the user for 5 inputs
for (int index = 0; index < input.length; index++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[index] = s.nextInt();
//check to see if the number is valid
if (min <= input[index] && input[index] <= max) {
//loop through the arrayone to determine where it is
for(int i = 0; i < arrayone.length; i++) {
//if it is not in the current index at i increment the loop count
if (arrayone[i] != input[index]) {
loop++;
}
//we have found where it is and should break out of the loop
else {
break;
}
}
//check if we found it based on how much we incremented
if(i != arrayone.length)
{
//output how long it took to find the number
System.out.println("It took " + loop + " time(s) to find the number " + input[index]);
}
else
{
System.out.println(input[index] + " not found!");
}
//now reinitialize the loop to 0 for the next guess
loop = 0;
}
}
//always remember to close your scanners
s.close();
}
}
int[] input = new int[0];
This creates an array with size of 0, so when you try save value it throws an exception because you are exceeding array size.
Solution: set valid size of array or use list.
The ArrayList is (simplifying) resizeable version of array. Use it like this:
List<Integer> input = new ArrayList<>();
input.add(5); //Adds 5 to list
input.get(0); //Read object of index 0
for(int value : list) { //Loop: for each element in list ...
System.out.println(value);
}
//Checks whether list contains 5
System.out.println(list.contains(5));
Also, do you actually need input to be an array? Because right now it looks like you don't need it at all.

Finding how many times an item Appears in an Array

Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}

Categories

Resources