how to get minimum in 2d array java - java

I need help, please! I am building up the following code to extract the minimum value of each column of the distance
I have tried to compute the code but to no avail
public static void main(String[] args) {
int data[] = {2, 4, -10, 12, 3, 20, 30, 11};//,25,17,23}; // initial data
int noofclusters = 3;
int centroid[][] = new int[][]{
{0, 0, 0},
{2, 4, 30}
};
getCentroid(data, noofclusters, centroid);
}
public static int[][] getCentroid(int[] data, int noofclusters, int[][] centroid) {
int distance[][] = new int[noofclusters][data.length];
int cluster[] = new int[data.length];
int clusternodecount[] = new int[noofclusters];
centroid[0] = centroid[1];
centroid[1] = new int[]{0, 0, 0};
System.out.println("========== Starting to get new centroid =========");
for (int i = 0; i < noofclusters; i++) {
for (int j = 0; j < data.length; j++) {
//System.out.println(distance[i][j]+"("+i+","+j+")="+data[j]+"("+j+")-"+centroid[0][i]+"="+(data[j]-centroid[0][i]));
distance[i][j] = Math.abs(data[j] - centroid[0][i]);
System.out.print(distance[i][j] + " ,");
}
System.out.println();
}
int[] result = new int[distance.length];
for (int i = 0; i < distance.length; i++) {
//int min = distance;
int min = distance[i][0];
for (int j = 0; j < distance[0].length; j++) {
if (distance[i][j] < min) {
min = distance[i][j];
}
result[j] = min;
System.out.println(result[j] + ", ");
}
}
return result;
}
}
The result of the computation for distance gives
row 1: 0 ,2 ,12 ,10, 1 ,18 ,28 ,9
row 2: 2 ,0 ,14 ,8 , 1 ,16 ,26 ,7
row 3: 28,26,40 ,18, 27 ,10 ,0 ,19
I want to go through each column to get the minimum value
0 0 12 8 1 10 0 7
Thanks for your help in advance

To get the minimum value in each column, first, you need to iterate the column in the outer loop. By doing so, we can access the matrix colunm-wise.
Assign the first value of each column to a variable. Then iterate through the rows in the inner loop.
Check if the current value is less than the minimum value. If so, assign the smallest value to minimum.
When we use an array, we get an array of minimum values of the column.
To obtain the minimun value in each row, swap the loops and use min[i].
Below is an example code:
int []min = new int[column_lenght];
for(int j = 0; j < column_length; j++) {
min[j] = array[i][j];
for(int i = 0; i < row_length; i++) {
if(array[i][j] < min[j]) {
min[j] = array[i][j];
}
}
}
The min[] will contain the minimum value of each column.

Related

Get the maximum summation of 2D array

There is a 2D array. int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}} . I want to get summation of each columns and get the maximum number. Finally it should be returned {5,7,8,9} . Because it has the maximum summation. I have mentioned i tried code below and it not return correct value. Help me to solve this
Your k is supposed to track the index with the greatest sum. So when you are resetting max you need to say k=i. You said i=k by mistake. Changing it makes your program run as desired.
EDIT: There was once code in the original question, to which this solution referred.
If the max column is expected, then I might have a solution:
import java.util.Arrays;
public class ArrayTest {
public static void main(String args[]) {
/*
* 1 3 4 1
* 5 7 8 9
* 6 1 2 1
*
*/
int[][] arr = {{1, 3, 4, 1}, {5, 7, 8, 9}, {6, 1, 2, 1}};
int m = arr.length;
int n = arr[0].length;
int[] arr2 = new int[n];
int p = 0;
int[][] colArray = new int[n][m];
for (int i = 0; i < n; i++) {
int[] arr_i = new int[m];
//System.out.println("i = " + i);
//System.out.println("p = " + p);
int sum = 0;
for (int j = 0; j < m; j++) {
arr_i[j] = arr[j][p];
sum += arr_i[j];
}
//System.out.println("Col: " + p + " : " + Arrays.toString(arr_i));
colArray[i] = arr_i;
arr2[p] = sum;
p++;
}
System.out.println("Sum: " + Arrays.toString(arr2));
int k = 0;
int max = arr2[0];
for (int i = 0; i < 3; i++) {
if (arr2[i] > max) {
max = arr2[i];
k = i;
}
}
System.out.println("Column index for max: " + k);
System.out.println("Column: " + Arrays.toString(colArray[k]));
}
}
Output:
Sum: [12, 11, 14, 11]
Column index for max: 2
Column: [4, 8, 2]
I recommend you find a way to break down your problem into smaller parts, solve each part with a function, then combine everything into a solution.
Example solution below:
public class Main {
public static long sum(int[] a){
long sum = 0;
for (int i : a) {
sum = sum + i;
}
return sum;
}
public static int[] withMaxSumOf(int[][] as){
// keep one sum for each array
long[] sums = new long[as.length];
// calculate sums
for (int i = 0; i < as.length; i++) {
int[] a = as[i];
sums[i] = sum(a);
}
// find the biggest one
int maxIndex = 0;
long maxSum = sums[0];
for (int i=1;i<sums.length;i++){
if (sums[i] > maxSum){
maxSum = sums[i];
maxIndex = i;
}
}
// return array that had biggest sum
return as[maxIndex];
}
public static void main(String[] args){
int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}};
// find the one with max sum
int[] max = withMaxSumOf(arr);
// print it
for (int i = 0; i < max.length; i++) {
int x = max[i];
if (i > 0) System.out.print(", ");
System.out.print(x);
}
System.out.println();
}
}
I think this might be your problem:
for(int i=0;i<3;i++) {
if(arr2[i]>max) {
max=arr2[i];
i=k;
}
}
I think that i=k really needs to be k=i.
Note also that it's worthwhile using better variable names. index instead of i, for instance. What is k? Call it "indexForHighestSum" or something like that. It doesn't have to be that long, but k is a meaningless name.
Also, you can combine the summation loop with the find-highest loop.
In the end, I might write it like this:
public class twoDMax {
public static void main(String args[]) {
int[][] arr= { {1,3,4,1}, {5,7,8,9}, {6,1,2,1} };
int indexForMaxRow = 0;
int previousMax = 0;
for(int index = 0; index < 4; ++index) {
int sum = 0;
for(int innerIndex = 0; innerIndex < 4; ++innerIndex) {
sum += arr[index][innerIndex];
}
if (sum > previousMax) {
previousMax = sum;
indexForMaxRow = index;
}
System.out.println(indexForMaxRow);
for(int index = 0; index < 4; ++index) {
System.out.println(arr[indexForMaxRow][index]);
}
}
}
I did a few other stylish things. I made use of more obvious variable names. And I am a little nicer about whitespace, which makes the code easier to read.
public static void main( String args[] ) {
int[][] arr = { { 1, 3, 4, 1 }, { 5, 7, 8, 9 }, { 6, 1, 2, 1 } };
int indexOfMaxSum = 0;
int maxSum = 0;
for ( int i = 0; i < arr.length; i++ ) {
int[] innerArr = arr[ i ]; // grab inner array
int sum = 0; // start sum at 0
for ( int j : innerArr ) {
// iterate over each int in array
sum += j; // add each int to sum
}
if ( sum > maxSum ) {
// if this sum is greater than the old max, store it
maxSum = sum;
indexOfMaxSum = i;
}
}
System.out.println( String.format( "Index %d has the highest sum with a sum of %d", indexOfMaxSum, maxSum ) );
int [] arrayWithLargestSum = arr[indexOfMaxSum]; // return me
}

Java Multidimensional array and integer occurrences

I have this integer array called numList which has
[4, 4, 3, 3, 3, 2, 1, 1, 1, 1, -1, -12, -12, -12, -12]
I would like to create a multidimensional array which can store
Which left side represents the number and the right side determines the number of occurrences.
The attempt i tried... i got nowhere.
// Declaring the new multi-dimensional array.
int [] [] newArray = new int [6] [2];
// Counter 3.
int counter3 = 0;
// Get first occurrence.
while (numList[counter3] < numList.length){
for (int counter3:numList){
newArray[] ([counter3]++);
}
Assuming your numbers are in order as they are in your example numList, then you could do this:
int[] numList = { 4, 4, 3, 3, 3, 2, 1, 1, 1, 1, -1, -12, -12, -12, -12 };
int[][] newArray = new int[6][2];
int index = 0;
for (int i = 0; i < numList.length;) {
int count = 0;
for (int x = 0; x < numList.length; x++)
if (numList[x] == numList[i]) count++;
newArray[index][0] = numList[i];
newArray[index][1] = count;
index++;
i += count;
}
for (int x = 0; x < newArray.length; x++) {
for (int i = 0; i < newArray[0].length; i++)
System.out.print(newArray[x][i] + " ");
System.out.println();
}
This way, you don't have to deal with imports as in the other answers (and this is shorter), but this only works if you have ordered numbers. There are some good sorting algorithms out there, though.
Edit: I changed it so that it can take numbers in any order of any size.
int[] numList = { 6, 6, 5, 5, 4, 4, 3, 2, 1, 1, 1, 7, 6, 5, 7, 8, 65, 65, 7 };
int[][] newArray = new int[1][2];
int index = 0;
for (int i = 0; i < numList.length;) {
try {
int count = 0;
boolean isUnique = true;
for (int x = 0; x < i; x++)
if (numList[x] == numList[i]) {
isUnique = false;
break;
}
if (isUnique) {
for (int x = 0; x < numList.length; x++)
if (numList[x] == numList[i]) count++;
newArray[index][0] = numList[i];
newArray[index][1] = count;
index++;
}
i++;
} catch (ArrayIndexOutOfBoundsException e) {
int tmpArray[][] = newArray;
newArray = new int[tmpArray.length + 1][tmpArray[0].length];
for (int row = 0; row < tmpArray.length; row++)
for (int col = 0; col < 2; col++)
newArray[row][col] = tmpArray[row][col];
}
}
for (int x = 0; x < newArray.length; x++) {
for (int i = 0; i < newArray[0].length; i++)
System.out.print(newArray[x][i] + " ");
System.out.println();
}
So, at this point, it would probably be shorter to use the maps from the other answer. The only benefit of my second answer not worrying about imports.
private Map<Integer, Integer> segregateArray(List<Integer> list) {
Map<Integer, Integer> result = new HashMap<>();
for (Integer i : list) {
if (result.containsKey(i)) {
result.put(i, result.get(i) + 1);
} else {
result.put(i, 1);
}
}
return result;
}
This should work. If you still need to return array use this:
private int[][] segregateArray(int[]list) {
Map<Integer, Integer> resultHelper = new HashMap<>();
for (int i : list) {
if (resultHelper.containsKey(i)) {
resultHelper.put(i, resultHelper.get(i) + 1);
} else {
resultHelper.put(i, 1);
}
}
int[][] result = new int[resultHelper.size()][2];
int arrayIterator=0;
for(Integer key : resultHelper.keySet())
{
result[arrayIterator][0]=key;
result[arrayIterator][1]=resultHelper.get(key);
arrayIterator++;
}
return result;
}
In the real life project you probably should avoid implementing a functionality like this yourself using a low level array mechanism (you added an extensive test suite, didn't you? :) and opt for one of available libraries.
In Java 8 this can be done nicely using closures similarly to what has been described here: Count int occurrences with Java8.
In Java 7 and earlier I would use one of the collection libraries such as Guava, which contains a Multiset collection delivering exactly what you're after.

Java array removal gives unexpected results?

The following code is part of a program which takes the values of array ar except for variable z, and copies it onto a different array called ar2. The result should be all the numbers except negative two (19, 1, 17, 17), but currently the result is 19 1 17 17 -2 19 1 17 17 -2 19 1 17 17 -2 19 1 17 17 -2.
public class Second_tiny {
public static void main(String[] args) {
int[] ar = { 19, 1, 17, 17, -2 };
int z = ar[0];
for (int i = 0; i < (ar.length); i++) {
if (z > ar[i]) {
z = ar[i];
}
}
// second pass
int[] ar2 = new int[ar.length];
int zero = 0;
for (int x = 0; x < (ar.length); x++) {
if (ar[x] == z) {
continue; // If it is equal to z go back to the loop again
}
ar2[zero++] = ar[x];
for (int i = 0; i < ar.length; i++) {
System.out.println(ar[i]);
}
/*
* //2nd pass copy all items except smallest one to 2nd array int[] ar2= new int[ar.length-1]; int curIndex = 0; for (i=0; i<ar.length; i++) { if (ar[i]==z) continue; ar2[curIndex++] =
* ar[i]; }
*/
}
}
}
Java 8 way:
int[] ar = { 19, 1, 17, 17, -2 };
int min = Arrays.stream(ar).min().getAsInt();
int[] ar2 = Arrays.stream(ar).filter(s -> s!=min).toArray();
System.out.println(Arrays.toString(ar2));
You're printing out your original array 4 times in this block:
for (int i = 0; i < ar.length; i++) {
System.out.println(ar[i]);
}
That block should be outside of your loop, and should reference ar2 instead of ar.
for (int x = 0; x < (ar.length); x++) {
if (ar[x] == z) {
continue; // If it is equal to z go back to the loop again
}
ar2[zero++] = ar[x];
}
for (int i = 0; i < ar2.length; i++) {
System.out.println(ar2[i]);
}
This will give you the following result:
19
1
17
17
0
The last 0 appears because 0 is the default value for ints. Your ar2 array is 5 elements long, and for the last element the default value is never replaced.
You could use Math.min(int, int) to determine your lowest value. Your second array should be one element smaller. I suggest guarding against removing more than one value. And you could use Arrays.toString(int[]) to print the second array. Something like,
int[] ar = { 19, 1, 17, 17, -2 };
int z = ar[0];
for (int i = 1; i < ar.length; i++) {
z = Math.min(z, ar[i]);
}
// second pass
int[] ar2 = new int[ar.length - 1];
boolean first = true;
for (int x = 0; x < ar.length; x++) {
if (ar[x] == z && first) {
first = false;
continue; // If it is equal to z go back to the loop again
}
int y = x - (!first ? 1 : 0);
ar2[y] = ar[x];
}
System.out.println(Arrays.toString(ar2));
Output is
[19, 1, 17, 17]
you code is right mistakenly you have given one extra for loop.i have done comment on that for loop.use the following code u will get the desired output.
public class HelloWorld {
public static void main(String[] args) {
int[] ar = { 19, 1, 17, 17, -2 };
int z = ar[0];
for (int i = 0; i < (ar.length); i++) {
if (z > ar[i]) {
z = ar[i];
}
}
// second pass
int[] ar2 = new int[ar.length];
int zero = 0,i=0;
for (int x = 0; x < (ar.length); x++) {
if (ar[x] == z) {
continue; // If it is equal to z go back to the loop again
}
ar2[zero++] = ar[x];
// for (int i = 0; i < ar.length; i++) {
System.out.println(ar[i]);
i++;
// }
/*
* //2nd pass copy all items except smallest one to 2nd array int[] ar2= new int[ar.length-1]; int curIndex = 0; for (i=0; i<ar.length; i++) { if (ar[i]==z) continue; ar2[curIndex++] =
* ar[i]; }
*/
}
}
}
output is:
19
1
17
17

Adding the columns of a jagged 2D array

I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}

Printing out the least occurring elements in an array

OK, so I found this question from a few days ago but it's on hold and it won't let me post anything on it.
***Note: The values or order in the array are completely random. They should also be able to be negative.
Someone recommended this code and was thumbed up for it, but I don't see how this can solve the problem. If one of the least occurring elements isn't at the BEGINNING of the array then this does not work. This is because the maxCount will be equal to array.length and the results array will ALWAYS take the first element in the code written below.
What ways are there to combat this, using simple java such as below? No hash-maps and whatnot. I've been thinking about it for a while but can't really come up with anything. Maybe using a double array to store the count of a certain number? How would you solve this? Any guidance?
public static void main(String[] args)
{
int[] array = { 1, 2, 3, 3, 2, 2, 4, 4, 5, 4 };
int count = 0;
int maxCount = 10;
int[] results = new int[array.length];
int k = 0; // To keep index in 'results'
// Initializing 'results', so when printing, elements that -1 are not part of the result
// If your array also contains negative numbers, change '-1' to another more appropriate
for (int i = 0; i < results.length; i++) {
results[i] = -1;
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[j] == array[i]) {
count++;
}
}
if (count <= maxCount) { // <= so it admits number with the SAME number of occurrences
maxCount = count;
results[k++] = array[i]; // Add to 'results' and increase counter 'k'
}
count = 0; // Reset 'count'
}
// Printing result
for (int i : results) {
if (i != -1) {
System.out.println("Element: " + i + ", Number of occurences: " + maxCount);
}
}
}
credit to: https://stackoverflow.com/users/2670792/christian
for the code
I can't thumbs up so I'd just like to say here THANKS EVERYONE WHO ANSWERED.
You can also use an oriented object approach.
First create a class Pair :
class Pair {
int val;
int occ;
public Pair(int val){
this.val = val;
this.occ = 1;
}
public void increaseOcc(){
occ++;
}
#Override
public String toString(){
return this.val+"-"+this.occ;
}
}
Now here's the main:
public static void main(String[] args) {
int[] array = { 1,1, 2, 3, 3, 2, 2, 6, 4, 4, 4 ,0};
Arrays.sort(array);
int currentMin = Integer.MAX_VALUE;
int index = 0;
Pair[] minOcc = new Pair[array.length];
minOcc[index] = new Pair(array[0]);
for(int i = 1; i < array.length; i++){
if(array[i-1] == array[i]){
minOcc[index].increaseOcc();
} else {
currentMin = currentMin > minOcc[index].occ ? minOcc[index].occ : currentMin;
minOcc[++index] = new Pair(array[i]);
}
}
for(Pair p : minOcc){
if(p != null && p.occ == currentMin){
System.out.println(p);
}
}
}
Which outputs:
0-1
6-1
Explanation:
First you sort the array of values. Now you iterate through it.
While the current value is equals to the previous, you increment the number of occurences for this value. Otherwise it means that the current value is different. So in this case you create a new Pair with the new value and one occurence.
During the iteration you will keep track of the minimum number of occurences you seen.
Now you can iterate through your array of Pair and check if for each Pair, it's occurence value is equals to the minimum number of occurences you found.
This algorithm runs in O(nlogn) (due to Arrays.sort) instead of O(n²) for your previous version.
This algorithm is recording the values having the least number of occurrences so far (as it's processing) and then printing all of them alongside the value of maxCount (which is the count for the value having the overall smallest number of occurrences).
A quick fix is to record the count for each position and then only print those whose count is equal to the maxCount (which I've renamed minCount):
public static void main(String[] args) {
int[] array = { 5, 1, 2, 2, -1, 1, 5, 4 };
int[] results = new int[array.length];
int minCount = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[j] == array[i]) {
results[i]++;
}
}
if (results[i] <= minCount) {
minCount = results[i];
}
}
for (int i = 0; i < results.length; i++) {
if (results[i] == minCount) {
System.out.println("Element: " + i + ", Number of occurences: "
+ minCount);
}
}
}
Output:
Element: 4, Number of occurences: 1
Element: 7, Number of occurences: 1
This version is also quite a bit cleaner and removes a bunch of unnecessary variables.
This is not as elegant as Iwburks answer, but I was just playing around with a 2D array and came up with this:
public static void main(String[] args)
{
int[] array = { 3, 3, 3, 2, 2, -4, 4, 5, 4 };
int count = 0;
int maxCount = Integer.MAX_VALUE;
int[][] results = new int[array.length][];
int k = 0; // To keep index in 'results'
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[j] == array[i]) {
count++;
}
}
if (count <= maxCount) {
maxCount = count;
results[k++] = new int[]{array[i], count};
}
count = 0; // Reset 'count'
}
// Printing result
for (int h = 0; h < results.length; h++) {
if (results[h] != null && results[h][1] == maxCount ) {
System.out.println("Element: " + results[h][0] + ", Number of occurences: " + maxCount);
}
}
Prints
Element: -4, Number of occurences: 1
Element: 5, Number of occurences: 1
In your example above, it looks like you are only using ints. I would suggest the following solution in that situation. This will find the last number in the array with the least occurrences. I assume you don't want an object-oriented approach either.
int [] array = { 5, 1, 2, 40, 2, -1, 3, 2, 5, 4, 2, 40, 2, 1, 4 };
//initialize this array to store each number and a count after it so it must be at least twice the size of the original array
int [] countArray = new int [array.length * 2];
//this placeholder is used to check off integers that have been counted already
int placeholder = Integer.MAX_VALUE;
int countArrayIndex = -2;
for(int i = 0; i < array.length; i++)
{
int currentNum = array[i];
//do not process placeholders
if(currentNum == placeholder){
continue;
}
countArrayIndex = countArrayIndex + 2;
countArray[countArrayIndex] = currentNum;
int count = 1; //we know there is at least one occurence of this number
//loop through each preceding number
for(int j = i + 1; j < array.length; j++)
{
if(currentNum == array[j])
{
count = count + 1;
//we want to make sure this number will not be counted again
array[j] = placeholder;
}
}
countArray[countArrayIndex + 1] = count;
}
//In the code below, we loop through inspecting each number and it's respected count to determine which one occurred least
//We choose Integer.MAX_VALUE because it's a number that easily indicates an error
//We did not choose -1 or 0 because these could be actual numbers in the array
int minNumber = Integer.MAX_VALUE; //actual number that occurred minimum amount of times
int minCount = Integer.MAX_VALUE; //actual amount of times the number occurred
for(int i = 0; i <= countArrayIndex; i = i + 2)
{
if(countArray[i+1] <= minCount){
minNumber = countArray[i];
minCount = countArray[i+1];
}
}
System.out.println("The number that occurred least was " + minNumber + ". It occured only " + minCount + " time(s).");

Categories

Resources