Thread: Counting Duplicate Variables in an Array

1. Member Join Date
Oct 2008
Posts
3
Rep Power
0 Counting Duplicate Variables in an Array

I have a program that sorts integers in an array. I would like for the last method, printcount, to count the number of occurences of each element, but I don't know how. Any help would be much appreciated. I'm also having problems making a partially filled array, so that the array will not initialize and print the leftover elements.

Java Code:
package sortintegers;

import java.util.Scanner;

public class Main
{

public static void main(String[] args)
{

int maxNumberElements = 50;

Scanner reader = new Scanner(System.in);
System.out.println("Enter number of elements you want to enter:");
int input = reader.nextInt();
int index = 0;

System.out.println("Now enter in integers:");
int[] num = new int[maxNumberElements];

for(int i = 0; i < input; i++)
{
System.out.print("Enter integer: ");
num[index] = maxNumberElements;
index++;

}
selectionSort(num);
printArray(num);
}

private static void printArray(int[] a)
{
for (int i : a)
System.out.print(i + " ");
System.out.println("");
}

private static void selectionSort(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
int minIndex = findMaximum(a, i);
if (minIndex != i)
swap(a, i, minIndex);
}
}

private static int findMaximum(int[] a, int first)
{
int minIndex = first;

for (int i = first + 1; i < a.length; i++)
if (a[i] > a[minIndex])
minIndex = i;

return minIndex;
}

private static void swap(int[] a, int x, int y)
{
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
private static void printCount(int a[])
{
int count = 0;
int store;
for (int i = count + 1; i < a.length; i++)
a[i] = store;

}
}  Reply With Quote

2. Simply count each element at a time and go through the whole array.  Reply With Quote

3. To design your counting code decide How you are going to store and report the counts?
One way would be to use a hashtable with the key being the item being counted and the value being the count.  Reply With Quote Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•