Given problem:
n items, each having a value val, a weight w, and an volume vol. Basically the same as knapsack 0/1 problem however the task is to find the maximum value V you can get in the knapsack but the weight can't be more than W_max and also the volume needs to be at least Vol_min.
The value, weight and volume are given in three arrays:
val[n+1], w[n+1], vol[n+1]
The i-th item has value val[i], weight w[i] and volume vol[i]
I know how to solve the normal 0/1 knapsack problem with only one limit but I'm not sure how to solve this one. I was thinking of using a 3D DP table but how is an entry in the table defined?
Here's what I've tried so far:
static int knapsack(int[] vol, int[] w, int[] val, int n, int Vol_min, int W_max) {
int[][][] DP = new int[n+1][W_max][Vol_min];
for(int i = 1; i < n+1; i++) {
for(int j = 0; j < W_max; j++) {
for(int k = 0; k < Vol_min; k++) {
if(w[i] > W_max) {
DP[i][j][k] = DP[i-1][j][k];
} else {
if(j - w[i] >= 0 && k + vol[i] <= n) {
DP[i][j][k] = Math.max(DP[i-1][j][k], DP[i-1][j - w[i]][k + vol[i]] + val[i]);
} else {
DP[i][j][k] = DP[i-1][j][k];
}
}
}
}
}
return DP[n][n][n];
}
Here is an example of the problem:
n = 6, Vol_min = 10, W_max = 12
vol = {1, 3, 7, 5, 1, 3}, w = {4, 5, 10, 2, 1, 4}, val = {10, 8, 5, 3, 1, 2}
=> Result: 22
So using recursive DP, I came up with a pretty standard solution for 1/0 Knapsack with a slight modification.
public static int[][] dp;// Item number, Weight, Volume
public static int[] vol, w, val;
public static int Vol_min, W_max, n;
static int knapsack(int item, int weight, int volume) {
// See if we have calculated this item before
if (dp[item][weight] == -1) {
// Set initial value to -2 (invalid result)
int max = -2;
// Iterate though all items past current item
for (int i = item; i < n; i++) {
// Make sure we don't go over max weight
if (weight + w[i] <= W_max) {
// Get the result of taking ith item
int res = knapsack(i + 1, weight + w[i], volume + vol[i]);
// Make sure result is valid (Total volume is greater than
// Vol_min)
if (res != -2) {
// If the result is valid take the max
max = Math.max(res + val[i], max);
}
}
}
if (max == -2 && volume >= Vol_min)// No other items taken and over
// Vol_min
dp[item][weight] = 0;
else // Eveything else
dp[item][weight] = max;
}
// Return the value
return dp[item][weight];
}
public static void main(String[] args) {
n = 6;
Vol_min = 10;
W_max = 12;
vol = new int[] { 1, 3, 7, 5, 1, 3 };
w = new int[] { 4, 5, 10, 2, 1, 4 };
val = new int[] { 10, 8, 5, 3, 1, 2 };
dp = new int[n + 1][W_max + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= W_max; j++) {
dp[i][j] = -1;
}
}
System.out.println(knapsack(0, 0, 0));
}
So imagine that we had a magical function knapsack(item,weight,volume) that could return the largest valid value of items that could be taken given the item number, weight and volume.
The solution would then iterate though every item after it and see what the answer would be and take the largest one. Similar to the 1/0 DP that you do. However, you realize that you don't need to keep track of the volume in the dp array hence it being only 2D. You only need to keep track of the volume at the end when you see that there are no more items that can be taken. Then you check to see if the solution is valid.
Related
I have a given matrix called m and its dimensions are n by n and it contains whole numbers. I need to copy the numbers that appear just once to a new array called a.
I think the logic would be to have a for loop for each number in the matrix and compare it to every other number, but I don't know how to actually do that with code.
I can only use loops (no maps or such) and this is what I've come up with:
public static void Page111Ex14(int[][] m) {
int previous = 0, h = 0;
int[] a = new int[m.length*m[0].length];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
previous = m[i][j];
if (m[i][j] != previous) {
a[h] = m[i][j];
h++;
}
}
}
It's probably not correct though.
Loop through it again to see if there's any repeated one. Assuming you can use labels, the answer might look a bit like that:
public static int[] getSingleInstanceArrayFromMatrix(int[][] m) {
int[] a = new int[m.length * m[0].length];
// Main loop.
for (int x = 0; x < m.length; x++) {
for (int y = 0; y < m[0].length; y++) {
// Gets the current number in the matrix.
int currentNumber = m[x][y];
// Boolean to check if the variable appears more than once.
boolean isSingle = true;
// Looping again through the array.
checkLoop:
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
// Assuring we are not talking about the same number in the same matrix position.
if (i != x || j != y) {
// If it is equal to our current number, we can update the variable and break.
if (m[i][j] == currentNumber) {
isSingle = false;
break checkLoop;
}
}
}
}
if (isSingle) {
a[(x * m.length) + y] = currentNumber;
}
}
}
return a;
}
Not sure if it's the most efficient, but I think it will work. It's somewhat hard to form your final array without the help of Lists or such. Since the unassigned values will default to 0, any actual zero (i.e. it's "supposed" to be there based on the matrix) will be undetected if you look up the returned array. But if there's such limitations I imagine that it's not crucially important.
This is one of those problems you can just throw a HashMap at and it just does your job for you. You traverse the 2d array, use a HashMap to store each element with its occurence, then traverse the HashMap and add all elements with occurence 1 to a list. Then convert this list to an array, which is what you're required to return.
This has O(n*n) complexity, where n is one dimension of the square matrix m.
import java.util.*;
import java.io.*;
class GetSingleOccurence
{
static int[] singleOccurence(int[][] m)
{
// work with a list so that we can append to it
List<Integer> aList = new ArrayList<Integer>();
HashMap<Integer, Integer> hm = new HashMap<>();
for (int row = 0; row < m.length; row++) {
for (int col = 0; col < m[row].length; col++) {
if (hm.containsKey(m[row][col]))
hm.put(m[row][col], 1 + hm.get(m[row][col]));
else
hm.put(m[row][col], 1);
}
}
for (Map.Entry entry : hm.entrySet())
{
if (Integer.parseInt(String.valueOf(entry.getValue())) == 1)
a.add(Integer.parseInt(String.valueOf(entry.getKey())));
}
// return a as an array
return a.toArray(new int[a.size()]);
}
public static void main(String args[])
{
// A 2D may of integers with some duplicates
int[][] m = { { 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 12, 14, 15 },
{ 16, 17, 18, 18, 20 },
{ 21, 22, 23, 24, 25 } };
a = singleOccurence(m);
}
}
It may be better to use a boolean array boolean[] dups to track duplicated numbers, so during the first pass this intermediate array is populated and the number of singles is counted.
Then create the resulting array of appropriate size, and if this array is not empty, in the second iteration over the dups copy the values marked as singles to the resulting array.
public static int[] getSingles(int[][] arr) {
int n = arr.length;
int m = arr[0].length;
boolean[] dups = new boolean[n * m];
int singles = 0;
for (int i = 0; i < dups.length; i++) {
if (dups[i]) continue; // skip the value known to be a duplicate
int curr = arr[i / m][i % m];
boolean dup = false;
for (int j = i + 1; j < dups.length; j++) {
if (curr == arr[j / m][j % m]) {
dup = true;
dups[j] = true;
}
}
if (dup) {
dups[i] = true;
} else {
singles++;
}
}
// debugging log
System.out.println("singles = " + singles + "; " + Arrays.toString(dups));
int[] res = new int[singles];
if (singles > 0) {
for (int i = 0, j = 0; i < dups.length; i++) {
if (!dups[i]) {
res[j++] = arr[i / m][i % m];
}
}
}
return res;
}
Test:
int[][] mat = {
{2, 2, 3, 3},
{4, 2, 0, 3},
{5, 4, 2, 1}
};
System.out.println(Arrays.toString(getSingles(mat)));
Output(including debugging log):
singles = 3; [true, true, true, true, true, true, false, true, false, true, true, false]
[0, 5, 1]
Your use of previous is merely an idea on the horizon. Remove it, and fill the one dimensional a. Finding duplicates with two nested for-loops would require n4 steps. However if you sort the array a, - order the values - which costs n² log n², you can find duplicates much faster.
Arrays.sort(a);
int previous = a[0];
for (int h = 1; h < a.length; ++h) {
if (a[h] == previous)...
previous = a[h];
...
It almost looks like this solution was already treated in class.
It doesn't look good:
previous = m[i][j];
if (m[i][j] != previous) {
a[h] = m[i][j];
h++;
}
you assigned m[i][j] to previous and then you check if if (m[i][j] != previous)?
Are there any limitations in the task as to the range from which the numbers can come from?
Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that an element of the array can be chosen only once to get sum S.
Example:
Input: arr[] = {25, 10, 5}, S = 30
Output: 2
Explanation:
Minimum possible solution is 2, (25+5)
Example:
Input: arr[] = {2, 1, 4, 3, 5, 6}, Sum= 6
Output: 1
Explanation:
Minimum possible solution is 1, (6)
I have found similar solution here but it says element of array can be used multiple times.
I have this code from the link which uses an array element multiple times, but how to restrict this to use only once?
static int Count(int S[], int m, int n)
{
int [][]table = new int[m + 1][n + 1];
// Loop to initialize the array
// as infinite in the row 0
for(int i = 1; i <= n; i++)
{
table[0][i] = Integer.MAX_VALUE - 1;
}
// Loop to find the solution
// by pre-computation for the
// sequence
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
if (S[i - 1] > j)
{
table[i][j] = table[i - 1][j];
}
else
{
// Minimum possible for the
// previous minimum value
// of the sequence
table[i][j] = Math.min(table[i - 1][j],
table[i][j - S[i - 1]] + 1);
}
}
}
return table[m][n];
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 9, 6, 5, 1 };
int m = arr.length;
System.out.print(Count(arr, m, 11));
}
The idiomatic approach for this is to loop backwards when updating the table of previous results.
static int minElementsForSum(int[] elems, int sum){
int[] minElems = new int[sum + 1];
for(int i = 1; i <= sum; i++) minElems[i] = Integer.MAX_VALUE;
for(int elem: elems)
for(int i = sum; i >= elem; i--)
if(minElems[i - elem] != Integer.MAX_VALUE)
minElems[i] = Math.min(minElems[i], minElems[i - elem] + 1);
return minElems[sum];
}
Demo
I have a code that sums the consecutive even numbers and consecutive odd numbers, then adds them to an arraylist. This process should be repeated until there are no more consecutive odd or even numbers in the list. Then returns the size of the arraylist.
I used nested for loops and the problem is the loops check the same index which doesn't make sense.
Here's my code:
public static int SumGroups(int[] arr) {
ArrayList<Integer> arl = new ArrayList<Integer>();
int even = 0, odd = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] % 2 == 0) {
even += arr[i];
if (arr[j] % 2 == 0) {
even += arr[j];
} else {
arl.add(even);
even = 0;
break;
}
} else {
odd += arr[i];
if (arr[j] % 2 != 0) {
odd += arr[j];
} else {
arl.add(odd);
odd = 0;
break;
}
}
}
}
return arl.size();
}
My Question is:
How to prevent loops from checking the same index ?
in other words, how to make my code sums the consecutive even numbers and consecutive odd numbers ?
Input:
int arr[]={2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9};
Output:
6 // [2, 1, 10, 5, 30, 15]
I think the following code should solve the problem, if you do not want to output the size simply return `sums` instead of `sums.size()`
public static int sumGroupsRecursively(int[] arr) {
List<Integer> numbersToSum = IntStream.of(arr).boxed().collect(Collectors.toList());
List<Integer> currentSumList = sumSublist(numbersToSum);
List<Integer> nextSumList = sumSublist(currentSumList);
while (currentSumList.size() != nextSumList.size()) {
currentSumList = nextSumList;
nextSumList = sumSublist(currentSumList);
}
return nextSumList.size();
}
public static List<Integer> sumSublist(List<Integer> list) {
int current = list.get(0);
int currentSum = 0;
List<Integer> sums = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (current % 2 == list.get(i) % 2) {
currentSum += list.get(i);
} else {
sums.add(currentSum);
current = list.get(i);
currentSum = current;
}
}
sums.add(currentSum);
return sums;
}
If you need to do this in one function what I would discourage because it is harder to read you could use code like this.
public static Integer sumSublist(int[] arr) {
List<Integer> sums = new ArrayList<>();
sums.add(0);
int i = 0;
while (i < arr.length - 1) {
int current = arr[i];
int currentSum = 0;
while (current % 2 == arr[i] % 2) {
currentSum += arr[i];
if (i >= arr.length - 1) {
break;
}
i++;
}
if (currentSum % 2 == sums.get(sums.size()-1) % 2) {
sums.set(sums.size() - 1, sums.get(sums.size()-1) + currentSum);
} else {
sums.add(currentSum);
}
}
return sums.size();
}
You are entering your first for loop passing in arr. Inside the first for loop you enter a second for loop passing in arr a second time. This means that you enter the second for loop as many times as there are elements in arr and transverse arr in the second for loop every single time.
for example, if arr.length() was 2 you would transverse arr 3 times. Once in your outer for loop and twice (once for each element in arr) in your inner loop.
Second, by adding both the odd and even numbers to your arraylist, you are doing nothing but reconstructing arr but in an arraylist rather than array. Therefor, returning arl.size() is the exact same as returning arr.length() which is already known and much easier to do.
Despite that, here is how I would calculate the sum of the odd and evens. I add both to different arraylists. You'll need to figure out exactly what you need to return though because your description is off.
public void test(){
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
int testOfEven = 6;
int testOfOdd = 9;
int sumOfEven = 0;
int sumOfOdd = 0;
ArrayList evens = new ArrayList<Integer>();
ArrayList odds = new ArrayList<Integer>();
for(int i = 0; i < arr.length; i++)
{
if ((arr[i]%2) == 0)
{
evens.add(arr[i]);
sumOfEven += arr[i];
}
else
{
odds.add(arr[i]);
sumOfOdd += arr[i];
}
}
assertEquals(testOfEven, sumOfEven);
assertEquals(testOfOdd, sumOfOdd);
}
after playing some time, here is my version:
public static int SumGroups(final int[] arr) {
if (arr.length > 0) {
int n, sum, psum;
psum = sum = n = arr[0] & 1; // parity of first number in sequence
int s = 1; // at least one element in array
int f = 0; // discard first parity change
for (int i = 1; i < arr.length; i++) {
if (n == (arr[i] & 1)) {
sum = (sum + n) & 1; // both even or odd, just increase sum
} else {
s += (psum ^ sum) & f; // compare sums parity
psum = sum; // store current sum's parity
sum = n = arr[i] & 1; // new first number in sequence
f = 1; // do not discard sums parity next time
}
}
s += (psum ^ sum) & f; // array ended, check parity of last sum
return s;
}
return 0;
}
I've put comments, but still some additional notes:
basic idea is the same as #PKuhn, just checked for some edge cases (empty array, integer overflow)
we don't need to have array of sums, we need just previous sum and check parity of it with newly calculated one
sum = (sum + n) & 1 - we don't need to calculate whole sum, we need just parity of the sum
s += (psum ^ sum) & f - we need to increase swap counter only if parity changed, xor helps us to get 1 if changed and 0 if not
Here is the list of tests which I've used:
Assert.assertEquals(6, SumGroups(new int[] { 2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9 }));
Assert.assertEquals(6, SumGroups(new int[] { 0, 0, 0, 0, 2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9 }));
Assert.assertEquals(1, SumGroups(new int[] { 2, 3, 3 }));
Assert.assertEquals(1, SumGroups(new int[] { 2 }));
Assert.assertEquals(1, SumGroups(new int[] { 2, 2 }));
Assert.assertEquals(1, SumGroups(new int[] { 2, 3, 3, 3, 3, 2 }));
Assert.assertEquals(2, SumGroups(new int[] { 3, 2, 2 }));
Assert.assertEquals(2, SumGroups(new int[] { 1, 3, 3, 2, 2 }));
Assert.assertEquals(2, SumGroups(new int[] { 1, 2, 3, 3, 2, 3, 3, 2 }));
Assert.assertEquals(1, SumGroups(new int[] { 3, 3, 2, 2 }));
Assert.assertEquals(1, SumGroups(new int[] { Integer.MAX_VALUE, Integer.MAX_VALUE }));
Assert.assertEquals(1, SumGroups(new int[] { Integer.MAX_VALUE, Integer.MAX_VALUE, 2 }));
Assert.assertEquals(1, SumGroups(new int[] { Integer.MAX_VALUE, Integer.MAX_VALUE, 3 }));
public void findEvenOdd(int a[]){
Boolean flip = false;
int sum = 0, i, m = 0;
for (i = 0; i < a.length; i++) {
if (flip) {
System.out.print(sum + "\t");
sum = a[i];
flip = !flip;
if (i + 1 < a.length && (a[i] % 2 != a[i + 1] % 2))
flip = !flip;
m++;
} else {
sum += a[i];
if (i + 1 < a.length && (a[i] % 2 != a[i + 1] % 2))
flip = !flip;
m++;
}
}
if(m!=a.length-1)
System.out.print(a[a.length-1] + "\t");
}
I have a code for nth largest element in a sorted matrix (sorted row and column wise increasing order)
I had some problem doing the (findNextElement) part in the code
i.e if the row is exhausted, then go up one row and get the next element in that.
I have managed to do that, but the code looks kind of complex. (My code does work and produces the output correctly) I will post my code here
k is the Kth largest element
m, n are matrix dimensions (right now it just supports NxN matrix but can be modified to support MxN)
public int findkthLargestElement(int[][] input, int k, int m, int n) {
if (m <=1 || n <= 1 || k > m * n) {
return Integer.MIN_VALUE;
}
int i = 0;
int j = 0;
if (k < m && k < n) {
i = m - k;
j = n - k;
}
PriorityQueue<Element> maxQueue = new PriorityQueue(m, new Comparator<Element>() {
#Override
public int compare(Element a, Element b) {
return b.value - a.value;
}
});
Map<Integer, Integer> colMap = new HashMap<Integer, Integer>();
for (int row = i; row < m; row++) {
Element e = new Element(input[row][n - 1], row, n - 1);
colMap.put(row, n - 1);
maxQueue.add(e);
}
Element largest = new Element(0, 0, 0);
for (int l = 0; l < k; l++) {
largest = maxQueue.poll();
int row = largest.row;
colMap.put(row, colMap.get(row) - 1);
int col = colMap.get(row);
while (col < j && row > i) {
row = row - 1;
colMap.put(row, colMap.get(row) - 1);
col = Math.max(0, colMap.get(row));
}
Element nextLargest = new Element(input[row][Math.max(0, col)], row, Math.max(0, col));
maxQueue.add(nextLargest);
}
return largest.value;
}
I need some help in the for loop specifically, please suggest me a better way to accomplish the task.
I have my code running here
http://ideone.com/wIeZSo
Ok I found a a simple and effective way to make this work, I changed my for loop to ths
for (int l = 0; l < k; l++) {
largest = maxQueue.poll();
int row = largest.row;
colMap.put(row, colMap.get(row) - 1);
int col = colMap.get(row);
if (col < j) {
continue;
}
Element nextLargest = new Element(input[row][Math.max(0, col)], row, Math.max(0, col));
maxQueue.add(nextLargest);
}
If we are exhausted with a column then we do not add anymore items till we reach an element from some other column.
This will also work for matrix which are only sorted row wise but not column wise.
In response to the comment: Even if there are duplicate elements, I don't think that it is necessary to use sophisticated data structures like priority queues and maps, or even inner classes. I think it should be possible to simply start at the end of the array, walk to the beginning of the array, and count how often the value changed. Starting with the value "infinity" (or Integer.MAX_VALUE here), after the kth value change, one has the kth largest element.
public class KthLargestElementTest
{
public static void main (String[] args) throws java.lang.Exception
{
testDistinct();
testNonDistinct();
testAllEqual();
}
private static void testDistinct()
{
System.out.println("testDistinct");
int[][] input = new int[][]
{
{1, 2, 3, 4},
{8, 9, 10, 11},
{33, 44, 55, 66},
{99, 150, 170, 200}
};
for (int i = 1; i <= 17; i ++)
{
System.out.println(findkthLargestElement(input, i, 4, 4));
}
}
private static void testNonDistinct()
{
System.out.println("testNonDistinct");
int[][] input = new int[][]
{
{ 1, 1, 1, 4 },
{ 4, 4, 11, 11 },
{ 11, 11, 66, 66 },
{ 66, 150, 150, 150 }
};
for (int i = 1; i <= 6; i++)
{
System.out.println(findkthLargestElement(input, i, 4, 4));
}
}
private static void testAllEqual()
{
System.out.println("testAllEqual");
int[][] input = new int[][]
{
{ 4, 4, 4, 4 },
{ 4, 4, 4, 4 },
{ 4, 4, 4, 4 },
{ 4, 4, 4, 4 }
};
for (int i = 1; i <= 2; i++)
{
System.out.println(findkthLargestElement(input, i, 4, 4));
}
}
public static int findkthLargestElement(
int[][] input, int k, int m, int n)
{
int counter = 0;
int i=m*n-1;
int previousValue = Integer.MAX_VALUE;
while (i >= 0)
{
int value = input[i/n][i%n];
if (value < previousValue)
{
counter++;
}
if (counter == k)
{
return value;
}
previousValue = value;
i--;
}
if (counter == k)
{
return input[0][0];
}
System.out.println("There are no "+k+" different values!");
return Integer.MAX_VALUE;
}
}
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).");