user2918968
user2918968

Reputation: 79

Finding out the frequency of unique numbers

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

Upvotes: 4

Views: 2159

Answers (6)

Charlie
Charlie

Reputation: 986

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

Upvotes: 0

josh
josh

Reputation: 407

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


}

}

Upvotes: 0

Akkusativobjekt
Akkusativobjekt

Reputation: 2023

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

    }

Upvotes: 0

siledh
siledh

Reputation: 3368

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.

Upvotes: 0

Moreno
Moreno

Reputation: 546

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!

Upvotes: 1

ManZzup
ManZzup

Reputation: 526

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

Upvotes: 0

Related Questions