Java - Read in 7 integers, count number of reoccurrances - java

I am taking an intro Java class and I'm stuck on an assignment. The goal is to write a program using single dimensional arrays that reads in 7 integers and then displays the number of times each value entered reoccurs (i.e. if you enter the number 12 twice, one of the output lines is "Number 12 occurs 2 times.")
I have some of it written already, but I'm stuck at how to count the number of times each array element occurs. I have an idea that I'm going to need a method and a second array, but I've hit a wall:
public class NumOfOccurrIn7 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Declare scanner and array
Scanner A = new Scanner(System.in);
int counter[] = new int[7];
System.out.print("Please enter 7 numbers: ");
//Populate initial array
for(int t = 0; t < 7; t++) {
counter[t] = A.nextInt();
}
//Process # of reoccurences and print results
for(int t=0; t<7; t++) {
}
for(int t=0; t<7; t++) {
System.out.print("Number " + counter[t] + " occurs " + x +
" times./n");
}
}
public static int CountOccurrance(int counter[]) {
}
}
Thank you for your feedback!

If the number 12 occurs twice, you don't want the output to print twice, so first you check if the number has already been processed. You do that by iterating over the array elements before t, and if one of them is the same as the current number, you don't print anything.
Next you check the rest of the array and count the number of times the current number occurs, then print the message.
// Process # of reoccurences and print results
for (int i = 0; i < 7; i++) {
boolean print = true;
int count = 0;
for (int j = 0; j < 7; j++) {
if (counter[j] == counter[i]) {
if (j < i) {
print = false;
break;
}
count++;
}
}
if (print) {
System.out.println("Number " + counter[i] +
" occurs " + count + " times.");
}
}

You can use Collections::frequency to count the occurrences e.g.
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
List<Integer> list = IntStream.of(nums).boxed().collect(Collectors.toList());
Set<Integer> set = new HashSet<Integer>(list);
for (int n : set) {
System.out.println("Frequency of " + n + " is " + Collections.frequency(list, n));
}
}
}
Output:
Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1
Another example of how you can count the duplicates is:
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
boolean duplicatesFound = false;
for (int n : nums) {
if (map.get(n) == null) {
map.put(n, 1);
} else {
map.put(n, map.get(n) + 1);
duplicatesFound = true;
}
}
if (duplicatesFound) {
System.out.println("Duplicates are as follows:");
map.entrySet().stream().filter(e -> e.getValue() > 1)
.forEach(e -> System.out.println(e.getKey() + " has occurred " + e.getValue() + " times."));
} else {
System.out.println("There are no duplicates in the list");
}
[Update]
Yet another solution (Thanks, #Andreas for the suggestion):
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
Map<Integer, Long> frequencyMap = Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(n -> n, Collectors.counting()));
frequencyMap.forEach((n, count) -> {
System.out.println("Frequency of " + n + " is " + count);
});
}
}
Output:
Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int counter[] = new int[7];
System.out.print("Please enter 7 numbers: ");
for (int t = 0; t < 7; t++) {
counter[t] = scanner.nextInt();
}
int[] occurrances = new int[counter.length];
label:
for (int t = 0; t < counter.length; t++) {
int counterValue = counter[t];
for (int i = 0; i < t; i++) {
if (counterValue == counter[i]) {
continue label;
}
}
occurrances[t] = 1;
for (int j = 0; j < counter.length; j++) {
if (j == t) {
continue;
}
int other = counter[j];
if (other == counterValue) {
occurrances[t]++;
}
}
if (occurrances[t] > 0) {
System.out.println("Number " + counter[t] + " occurs " + occurrances[t] + " times.");
}
}
}

Related

Make Folding an ArrayList to single integer

I'm Developing a Code for java to Fold the element inside an array with example
A[0] = 2, A[1] = 7, A[2] = 9, A[3] = 7
Then Fold it with this format
A[0] = (A[0] + A[3]) mod 10 = 9
A[1] = (A[1] + A[2]) mod 10 = 6
And Fold it again until single
A[0] = (A[0] + A[1]) mod 10 = 5
Below are incomplete code:
import java.util.ArrayList;
import java.util.List;
import java.lang.Math;
public class ArrayFolder {
public static void main(String[] args) {
//ArrayList
int[] A = {
2,
7,
9,
7
};
//To define a new Array later
List<Integer> intList = new ArrayList<Integer>();
//To print the ArrayList A
for (int x = 0; x < A.length; x++) {
System.out.println("A[" + x + "]= " + A[x]);
}
//Function to fold the ArrayList into half
int res = 0;
int result = 0;
//if A.length is Even
if (A.length % 2 == 0) {
for (int i = 0; i < A.length / 2; i++) {
res = A[i] + A[A.length - 1 - i];
result = res % 10;
intList.add(result);
}
}
//if A.length is Odd
else {
for (int i = 0; i < A.length / 2; i++) {
res = A[i] + A[A.length - 1 - i];
result = res % 10;
intList.add(result);
}
result = A[A.length / 2];
intList.add(result);
}
//add the int to New ArrayList
Integer[] intArray = new Integer[intList.size()];
intArray = intList.toArray(intArray);
System.out.println("\nNew Array ");
for (Integer s: intArray) {
System.out.println(s);
}
}
}
Compiled result
A[0]= 2
A[1]= 7
A[2]= 9
A[3]= 7
New Array
9
6
I couldn't find an efficient way to keep looping the function, so the code will stop folding when a single Integer achieved.
My question is, is there any efficient way to loop the process so later It can work with a larger element of Array?.
Kindly provide the logic or the code so I can continue with my code.
Many Thanks
You could put your folding algorithm into a separate method that returns you the folded array and call this method until you achieve a single Integer, for example like this:
import java.util.ArrayList;
import java.util.List;
public class ArrayFolder {
public static void main(String[] args) {
//ArrayList
Integer[] A = {
2,
7,
9,
7
};
while (A.length > 1) {
A = fold(A);
}
System.out.println("A[0]= " + A[0]);
}
private static Integer[] fold(Integer[] A) {
List<Integer> intList = new ArrayList<>();
//To print the ArrayList A
for (int x = 0; x < A.length; x++) {
System.out.println("A[" + x + "]= " + A[x]);
}
//Loop to fold the ArrayList into half
for (int i = 0; i < A.length / 2; i++) {
int res = A[i] + A[A.length - 1 - i];
int result = res % 10;
intList.add(result);
}
//if A.length is odd
if (A.length % 2 != 0) {
intList.add(A[A.length / 2]);
}
System.out.println("\n");
return intList.toArray(new Integer[intList.size()]);
}
}
You could also use a recursive method, i.e. the folding method will call itself for further folding until it reaches one Integer.
import java.util.ArrayList;
import java.util.List;
public class ArrayFolder {
public static void main(String[] args) {
//ArrayList
final Integer[] A = {
2,
7,
9,
7
};
fold(A);
}
private static void fold(Integer[] A) {
if (A.length > 0) {
List<Integer> intList = new ArrayList<>();
//To print the ArrayList A
for (int x = 0; x < A.length; x++) {
System.out.println("A[" + x + "]= " + A[x]);
}
//Loop to fold the ArrayList into half
for (int i = 0; i < A.length / 2; i++) {
int res = A[i] + A[A.length - 1 - i];
int result = res % 10;
intList.add(result);
}
//if A.length is odd
if (A.length > 1 && A.length % 2 != 0) {
intList.add(A[A.length / 2]);
}
System.out.println("\n");
fold(intList.toArray(new Integer[intList.size()]));
}
}
}
Folding in same array:
public static void main(String[] args) throws Exception {
int[] A = {2,7,9,7};
System.out.println("Input: " + Arrays.toString(A));
int length = A.length;
int mid = mid(length);
while(mid > 0) { //fold till only one left to fold
int i = 0;
for (; i <mid ; i++) { //single fold
int end = length-i-1;
if(i!=end) {
A[i] = (A[i] + A[end])%10;
}
}
System.out.println(Arrays.toString(Arrays.copyOf(A, mid)));
length = mid;
mid = mid(i);
}
System.out.println("Output: " + A[0]);
}
static int mid(int length) {
if(length == 1) return 0;
return (int)Math.ceil(length/2.0);
}
Output:
Input: [2, 7, 9, 7]
[9, 6]
[5]
Output: 5
For odd numbers:
Input: [2, 7, 3, 9, 7]
[9, 6, 3]
[2, 6]
[8]
Output: 8

Setting a number in range in arrays for java

While writing a code for printing out random numbers ranging from 0 to 99, I had faced some difficulties. I tried to change the condition in the for statement to e<100, however, it had occurred an error. Where should I put the conditions in order for my output to show numbers between 0 to 99?
public class EvensOdds {
public static void printArray(int[] ear) {
System.out.println("ODD NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 10);
if(ear[e]%2!=0)
System.out.print(ear[e] + " ");
}
System.out.println("\n" + "EVEN NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 10);
if(ear[e]%2==0)
System.out.print(ear[e] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] numberArray = new int[25];
printArray(numberArray);
}
}
In Java 8, below creates an array with size 25, with random entries between 0,99
Random random = new Random();
int[] array = random.ints(25, 0, 100).toArray();

determining how many times each integer appears in the input (array)

it keeps repeating regardless of whether it's been already calculated or not. You can see the example output. it already calculated the occurrence of 1, but when it sees 1 again, it will calculate it again!
public class SortingInLinearTime {
public static int[][] howMany(int[] n){
// Makes a double array list where the second value is occurrence of the first value.
int[][] a = new int[n.length][2];
int counter = 0;
for(int i = 0; i != n.length; i++){
for(int j = 0; j != n.length; j++) {
if(n[i] == n[j]){
counter++;
}
}
a[i][0] = n[i];
a[i][1] = counter;
counter = 0;
}
// printer helper function
for(int i = 0; i != n.length; i++){
System.out.print(a[i][0] + " occurs ");
System.out.println(a[i][1] + " times");
}
return a;
}
public static void main(String[] args) {
int[] testArray = {1, 2, 3, 1, 2, 3, 4};
System.out.print(howMany(testArray));
}
}
output:
1 occurs 2 times
2 occurs 2 times
3 occurs 2 times
1 occurs 2 times
2 occurs 2 times
3 occurs 2 times
4 occurs 1 times
[[I#15db9742
In the first loop with i, you are recounting the same values again and again.
1 appears when i = 0 and when i = 3 as well. you once counted for 1 when i == 0 and recounted again at i == 3 in array n.
However, I believe the best solution for your problem could be achieved by changing your data structure from int[][] to an hashmap.
You're making this way harder than it needs to be both by looping over the array twice and by using an array to store your result. Try this:
public class SortingInLinearTime {
public static Hashtable<Integer, Integer> howMany(int[] n){
Hashtable<Integer, Integer> toRet = new Hashtable<Integer, Integer>();
for (int i = 0; i < n.length; i++) {
if (!toRet .containsKey(n[i])) {
toRet.put(n[i], 1);
} else {
toRet.put(n[i], toRet.get(n[i]) + 1);
}
}
return toRet;
}
public static void main(String[] args) {
int[] testArray = {1, 2, 3, 1, 2, 3, 4};
Hashtable<Integer, Integer> counts = howMany(testArray);
Set<Integer> keys = counts.keySet();
for(Integer key : keys){
System.out.println(key + " occurs " + counts.get(key) + " times.");
}
}
}
This has several advantages. It will not break if you pass an array with large numbers, like {1, 11, 203, 203}, which your current implementation cannot handle. It does not use extra space by declaring an array with many elements that you do not need. Most important, it works.
Convert your array to list using Arrays.asList() and then use the collections api to get the count.
Collections.frequency(Collection c, Object o)
Updated with the implementation
import java.util.AbstractList;
import java.util.Collections;
import java.util.List;
public class SortingInLinearTime {
public static int[][] howMany( int[] n){
// Makes a double array list where the second value is occurrence of the first value.
int[][] a = new int[n.length][2];
for(int i = 0; i < n.length; i++){
int count = Collections.frequency(asList(n), n[i]);
a[i][0] = n[i];
a[i][1] = count;
}
// printer helper function
for(int i = 0; i < n.length; i++){
System.out.print(a[i][0] + " occurs ");
System.out.println(a[i][1] + " times");
}
return a;
}
public static List<Integer> asList(final int[] is)
{
return new AbstractList<Integer>() {
public Integer get(int i) { return is[i]; }
public int size() { return is.length; }
};
}
public static void main(String[] args) {
int[] testArray = {1, 2, 3, 1, 2, 3, 4};
System.out.print(howMany(testArray));
}
}

Identifying, if there's duplicated inputted integer in Java

How am I going to identify the duplicated inputted integer like If I input 1 1 2 3 4, it will say number 1 is been duplicated
import java.util.*;
public class Haha {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] items = new int[5];
int sum;
System.out.println("Enter five integers: ");
sum = 0;
for (int counter = 0; counter < items.length; counter++) {
items[counter] = console.nextInt();
sum = sum + items[counter];
}
System.out.println("The sum of the numbers = " + sum);
System.out.print("The numbers in the reverse" + "order are: ");
for (int counter = items.length - 1; counter >= 0; counter--) {
System.out.print(items[counter] + " ");
}
System.out.println();
}
}
All you need is a Set :)
int[] arr = { 1, 1, 2, 3, 4,3 };
Set<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
boolean b = hs.add(arr[i]); // add returns false if the value is already present in the set
if (!b) {
System.out.println("duplicate value is : " + arr[i]);
}
}
O/P :
duplicate value is : 1
duplicate value is : 3

Java Array sort by means of a comparator

The complete code can be found at: https://skydrive.live.com/redir?resid=7B7D2F11B13EF9C9!54468&authkey=!AD4fD8sGgc7oJIE
This is part of the code:
g_sorted = 0;
for (int l_loop = 0; l_loop < l_length; l_loop++)
{
if (!l_IntegerArray[l_loop].equals(g_exclude))
{
g_tag[g_sorted] = l_loop;
g_tosort_Integer[g_sorted] = l_IntegerArray[l_loop];
g_sorted++;
}
} // for (int l_loop = 0; l_loop < p_toSort; l_loop++)
Arrays.sort
(g_tag, 0, g_sorted, new Comparator<Integer>()
{
public int compare(Integer i1, Integer i2)
{
return Integer.compare(g_tosort_Integer[i1], g_tosort_Integer[i2]);
}
}
);
g_tosort_Integer, g_tag, g_tosort_Integer are 'Integer'.
g_exclude is used to exclude items which must not be part of the sort.
When no items are excluded (no item has the value equal to g_exclude or the if-statement is commented), everything works fine.
When 1 or more items are excluded I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at TestSort$1.compare(TestSort.java:53)
at TestSort$1.compare(TestSort.java:50)
at java.util.TimSort.binarySort(TimSort.java:265)
at java.util.TimSort.sort(TimSort.java:190)
at java.util.Arrays.sort(Arrays.java:727)
at TestSort.<init>(TestSort.java:48)
at TestSort.main(TestSort.java:71)
Can someone explain this to me ? Thanks.
This is how to solve. I kept your class "structure", but I took the liberty of changing variable names to get clearer what I was doing. You asked how to order an array not changing the order of elements, but changing a index upon it.
Here's the code.
public class TestSort {
int c_maxSort = 10000;
Integer[] unsortedAndFiltered = new Integer[c_maxSort];
Integer[] index = new Integer[c_maxSort];
public TestSort() {
Integer exclude = 0;
int newPosition;
int lengthOfOriginalArray;
Integer[] originalArray = { 5, 3, 0, 2, 7, 1, 5, 6, 8, 4 };
lengthOfOriginalArray = originalArray.length;
System.out.print("Original: ");
for (int i = 0; i < lengthOfOriginalArray; i++)
System.out.print(originalArray[i] + " ");
System.out.println(" - Length: " + lengthOfOriginalArray);
newPosition = 0;
for (int i = 0; i < lengthOfOriginalArray; i++) {
if (!originalArray[i].equals(exclude)) {
index[newPosition] = newPosition;
unsortedAndFiltered[newPosition] = originalArray[i];
newPosition++;
}
}
System.out.println("Tags: ");
for (int i = 0; i < newPosition; i++)
System.out.print(index[i] + " ");
System.out.println("");
System.out.println("Unsorted numbers: ");
for (int l_loop = 0; l_loop < newPosition; l_loop++)
System.out.print(unsortedAndFiltered[l_loop] + " ");
System.out.println("");
int deleted = lengthOfOriginalArray - newPosition;
Arrays.sort(index, 0, newPosition, new IndirectedComparator(unsortedAndFiltered, index));
System.out.println("Sorted Tags: ");
for (int i = 0; i < newPosition; i++)
System.out.print(index[i] + " ");
System.out.println("");
System.out.println("Sorted Numbers: ");
for (int i = 0; i < newPosition; i++)
System.out.print(unsortedAndFiltered[index[i]] + " ");
System.out.println("");
}
public static void main(String[] args) {
new TestSort();
}
}
where the comparator is coded like this:
public class IndirectedComparator implements Comparator<Integer> {
private Integer[] array;
private Integer[] index;
public IndirectedComparator(Integer [] array, Integer[] index){
this.array = array;
this.index = new Integer[index.length];
System.arraycopy(index, 0, this.index, 0, index.length);
}
#Override
public int compare(Integer i1, Integer i2) {
return Integer.compare(array[index[i1]], array[index[i2]]);
}
}
This is my execution:
Original: 5 3 0 2 7 1 5 6 8 4 - Length: 10
Tags:
0 1 2 3 4 5 6 7 8
Unsorted numbers:
5 3 2 7 1 5 6 8 4
Sorted Tags:
4 2 1 8 0 5 6 3 7
Sorted Numbers:
1 2 3 4 5 5 6 7 8

Categories

Resources