Finding all permutations to get the given sum (Coin change problem) - java

I am trying to solve a classical coin-change (dynamic) problem.
To find number of all unique combinations to get a sum from infinite denominations of coins using dynamic approach, i used this method:
/*
n - number of coins
arr[] - coin denominations
x - total sum
dp[] - array to store number of combinations at index i.
*/
for (int j = 0; j < n; j++)
for (int i = 1; i <= x; i++)
if (arr[j] <= i)
dp[i] = (long) ((dp[i] + dp[i - arr[j]]) % (1e9 + 7));
This gives me all unique possible combinations count:
Eg:
Input:
n=3 x=9
Coins: 2 3 5
Output:
3
So far ,all good.
But i observed that just by interchanging the loops in above snippet, i get all the possible permutations.
for (int i = 1; i <= x; i++)
for (int j = 0; j < n; j++)
if (arr[j] <= i)
dp[i] = (long) ((dp[i] + dp[i - arr[j]]) % (1e9 + 7));
This gives me all unique possible permutations count:
Eg:
Input:
3 9
2 3 5
Output:
8
With debugging and going through each iteration, i mapped a pattern that was formed, but didn't understand the reason behind why i am getting permutations.
Can any one explain me this iteratively. Any help will be appreciated.
Thanks
Both questions can be found here:
Permutations: Coin Combinations 1
Combinations: Coin Combinations 2

The first code with outer loop by coins updates number of ways to compose values dp[] with new coin at every round of outer loop. So after k-th round we have dp[] array filled with combinations of k coins only, and the rest of coins is not used yet. If we will store combinations themselves for sorted coin array, we will see only ordered ones like 1 1 5, and 5 never will go before 1. That is why combinations.
The second code at m-th round of outer loop fills m-th cell dp[m] using all possible coins. So we count for m=7 both 1 1 5 and 1 5 1 and 5 1 1 variants. That is why all permutations are counted here.
In addition for comment: we can make 2d array, where dp[x][c] contains number of permutations with sum x, ending with coin a[c]. Note that in this case we have to join counts of permutations with sum x-a[c]. For reference - 1d and 2d Python code.
def coins1(a, n): #permutations
count = [1]+[0]*n
for x in range(1, n + 1):
for c in a:
if (x-c >= 0):
count[x] += count[x-c]
return count[n]
def coins11(a, n): #permutations 2d
m = len(a)
count = [[1] + [0]*(m-1)] + [[0]*m for i in range(n)]
for x in range(1, n + 1):
for c in range(m):
if x>=a[c]:
count[x][c] += sum(count[x-a[c]])
return sum(count[n])

Related

Meaning of the formula how to find lost element in array?

The task is to find lost element in the array. I understand the logic of the solution but I don't understand how does this formula works?
Here is the solution
int[] array = new int[]{4,1,2,3,5,8,6};
int size = array.length;
int result = (size + 1) * (size + 2)/2;
for (int i : array){
result -= i;
}
But why we add 1 to total size and multiply it to total size + 2 /2 ?? In all resources, people just use that formula but nobody explains how that formula works
The sum of the digits 1 thru n is equal to ((n)(n+1))/2.
e.g. for 1,2,3,4,5 5*6/2 = 15.
But this is just a quick way to add up the numbers from 1 to n. Here is what is really going on.
The series computes the sum of 1 to n assuming they all were present. But by subtracting each number from that sum, the remainder is the missing number.
The formula for an arithmetic series of integers from k to n where adjacent elements differ by 1 is.
S[k,n] = (n-k+1)(n+k)/2
Example: k = 5, n = 10
S[k,n] = 5 6 7 8 9 10
S[k,n] = 10 9 8 7 6 5
S[k,n] = (10-5+1)*(10+5)/2
2S[k,n] = 6 * 15 / 2
S[k,n] = 90 / 2 = 45
For any single number missing from the sequence, by subtracting the others from the sum of 45, the remainder will be the missing number.
Let's say you currently have n elements in your array. You know that one element is missing, which means that the actual size of your array should be n + 1.
Now, you just need to calculate the sum 1 + 2 + ... + n + (n+1).
A handy formula for computing the sum of all integers from 1 up to k is given by k(k+1)/2.
By just replacing k with n+1, you get the formula (n+1)(n+2)/2.
It's simple mathematics.
Sum of first n natural numbers = n*(n+1)/2.
Number of elements in array = size of array.
So, in this case n = size + 1
So, after finding the sum, we are subtracting all the numbers from array individually and we are left with the missing number.
Broken sequence vs full sequence
But why we add 1 to total size and multiply it to total size + 2 /2 ?
The amount of numbers stored in your array is one less than the maximal number, as the sequence is missing one element.
Check your example:
4, 1, 2, 3, 5, 8, 6
The sequence is supposed to go from 1 to 8, but the amount of elements (size) is 7, not 8. Because the 7 is missing from the sequence.
Another example:
1, 2, 3, 5, 6, 7
This sequence is missing the 4. The full sequence would have a length of 7 but the above array would have a length of 6 only, one less.
You have to account for that and counter it.
Sum formula
Knowing that, the sum of all natural numbers from 1 up to n, so 1 + 2 + 3 + ... + n can also be directly computed by
n * (n + 1) / 2
See the very first paragraph in Wikipedia#Summation.
But n is supposed to be 8 (length of the full sequence) in your example, not 7 (broken sequence). So you have to add 1 to all the n in the formula, receiving
(n + 1) * (n + 2) / 2
I guess this would be similar to Missing Number of LeetCode (268):
Java
class Solution {
public static int missingNumber(int[] nums) {
int missing = nums.length;
for (int index = 0; index < nums.length; index++)
missing += index - nums[index];
return missing;
}
}
C++ using Bit Manipulation
class Solution {
public:
int missingNumber(vector<int> &nums) {
int missing = nums.size();
int index = 0;
for (int num : nums) {
missing = missing ^ num ^ index;
index++;
}
return missing;
}
};
Python I
class Solution:
def missingNumber(self, nums):
return (len(nums) * (-~len(nums))) // 2 - sum(nums)
Python II
class Solution:
def missingNumber(self, nums):
return (len(nums) * ((-~len(nums))) >> 1) - sum(nums)
Reference to how it works:
The methods have been explained in the following links:
Missing Number Discussion
Missing Number Solution

How would I loop over the permutations of N numbers with a given range, preferably without recursion?

I have N numbers, and a range, over which I have to permute the numbers.
For example, if I had 3 numbers and a range of 1-2, I would loop over 1 1 1, 1 1 2, 1 2 1, etc.
Preferably, but not necessarily, how could I do this without recursion?
For general ideas, nested loops don't allow for an arbitrary number of numbers, and recursion is undesireable due to high depth (3 numbers over 1-10 would be over 1,000 calls to the section of code using those numbers)
One way to do this, is to loop with one iteration per permuation, and use the loop variable to calculate the values that a permuation is made off. Consider that the size of the range can be used as a modulo argument to "chop off" a value (digit) that will be one of the values (digits) in the result. Then if you divide the loop variable (well, a copy of it) by the range size, you repeat the above operation to extract another value, ...etc.
Obviously this will only work if the number of results does not exceed the capacity of the int type, or whatever type you use for the loop variable.
So here is how that looks:
int [][] getResults(int numPositions, int low, int high) {
int numValues = high - low + 1;
int numResults = (int) Math.pow(numValues, numPositions);
int results[][] = new int [numResults][numPositions];
for (int i = 0; i < numResults; i++) {
int result[] = results[i];
int n = i;
for (int j = numPositions-1; j >= 0; j--) {
result[j] = low + n % numValues;
n /= numValues;
}
}
return results;
}
The example you gave in the question would be generated with this call:
int results[][] = getResults(3, 1, 2);
The results are then:
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2

How to create a new Array from Original Array in which the sum of all differences is maximum?

Candy Love
There are N children coming to the party and you have decided to distribute candies as return gift to those children. Children are numbered from 1 to N. You are given an array A which defines the maximum number of candies which can be given to any child. There are restrictions on number of candies which can be given to any child :
Each child should be given at least one candy.
The maximum candies which can be given to ith child is A[i].
The collective success of party is given by a function S which is calculated as follows :
function S():
Array C denotes the number of candies given to each child
sum = o
for i = 2 to N:
sum = sum a abs(c[i]-[i-1])
return sum
Now as the host of party you want to maximize the success of party. So distribute the candies in such a way which maximizes the success of party. Output the maximum value of success which can be obtained.
>##Sample Input##
You will be given N denoting the number of children in party and next line will consist of N space separated integers denoting the maximum candies which can be given to any child.
>##Sample Output##
Print the maximum success value of party which can be obtained.
>##Constraints##
2 <= N <= 10^5
1 <= A[i] <= 10^9
>##Sample Input 1##
3
1 2 4
>##Sample Output 1##
3
>##Sample Input 2##
6
3 10 15 10 3 10
>##Sample Output 2##
45
>##Explanation 1##
One of the ways to get success value as 3 is giving {1,2,4} candies to children respectively.
>##Explanation 2##
One of the ways to get success value as 45 is giving {1,10,1,10,1,10} candies to children respectively.
-to maximize the sum of differences each value X of the array should be changed to either 1 or X
import java.io.*;
class Test
{
static int maximumDifferenceSum(int arr[], int N)
{
int dp[][] = new int [N][2];
for (int i = 0; i < N; i++)
dp[i][0] = dp[i][1] = 0;
for (int i = 0; i< (N - 1); i++)
{
//dp[i][0] stores the maximum value of sum using first i elements if ith array value is modified to 1
dp[i + 1][0] = Math.max(dp[i][0],
dp[i][1] + Math.abs(1 - arr[i]));
//dp[i][1] stores the maximum value of sum using first i elements if ith array value is kept as a[i]
dp[i + 1][1] = Math.max(dp[i][0] +
Math.abs(arr[i + 1] - 1),
dp[i][1] + Math.abs(arr[i + 1]
- arr[i]));
}
return Math.max(dp[N - 1][0], dp[N - 1][1]);
}
public static void main (String[] args)
{
int arr[] = {3,10,15,10,3,10};
int N = arr.length;
// output will be 45
System.out.println( maximumDifferenceSum(arr, N));
}
}

3 Dice Sum Counting Program Java

For my Computer Science Class, my teacher is asking us to do the following:
Program Description: You are learning to play a new game that involves 3 six-sided die. You know that if you knew the probability for each of the possible rolls of the die that you’d be a much better competitor.
Since you have just been studying arrays and using them to count multiple items that this program should be a snap to write. This will be cool since the last time we did this we work just looking for how many times 9 or 10 could be rolled and this program won’t require any if statements.
Required Statements: output, loop control, array
Sample Output:
Number Possible Combinations
1 0
2 0
3 1
4 3
5 6
6 10
7 15
8 21
9 25
10 27
11 27
12 25
13 21
14 15
15 10
16 6
17 3
18 1
I can easily do this with an if statement, but I don't understand how to do it without one. It is especially tricky because under hints, she wrote: "These programs utilize a counting array. Each time a value is generated the position at that index is incremented. It’s like the reverse of the lookup table." I have no idea what this means.
Here's my code with the if statement:
public class prog410a
{
public static void main(String args[])
{
System.out.println("Number\tPossible Combinations");
for (int x = 1; x <= 18; x++)
{
int count = 0;
for (int k = 1; k <= 6; k++)
{
for (int i = 1; i <= 6; i ++)
{
for (int j = 1; j <= 6; j++)
{
if (k + i + j == x)
count++;
}
}
}
System.out.println(x + "\t\t\t" + count);
}
}
}
So I guess my overall question is this: How can I emulate this, but by using some sort of array instead of an if statement?
You don't need the outer x loop. All you need is three nested loops, one for each die. You will also need an array of integers all initialized to zero. Inside the innermost dice loop, you just use the sum of the three dice as the index to you integer array and increment the value at that index.
After you complete the dice loops, then you can iterate over your integer array and output the frequency of your results.
Since this is homework, I won't write the code for you, just give you the general outline.
Create a count array of size 18. Initialise all values to 0.
Have three nested loops counting from 1 to 6 exactly like your three inner loops. These represent the values on your dice.
Inside your innermost loop, add the three loop counters together. This is your dice total and you use it as an index into the count array to increment the value at that index.
After you exit the three nested loops, use another loop to iterate through the count array to print out the values.
This seems to work - and without if:
public void test() {
// Remember to -1 because arrays are accessed from 0 to length-1
int[] counts = new int[18];
// Dice 1.
for (int k = 1; k <= 6; k++) {
// Dice 2.
for (int i = 1; i <= 6; i++) {
// Dice 3.
for (int j = 1; j <= 6; j++) {
// Count their sum (-1 as noted above).
counts[i + j + k - 1] += 1;
}
}
}
// Print out the array.
System.out.println("Number\tPossible Combinations");
for (int i = 0; i < counts.length; i++) {
System.out.println("" + (i + 1) + "\t" + counts[i]);
}
}
Essentially you build the results in an array then output them.
From Wikipedia: In computer science, a lookup table is an array that replaces runtime computation with a simpler array indexing operation. The savings in terms of processing time can be significant, since retrieving a value from memory is often faster than undergoing an 'expensive' computation or input/output operation., this means that usually we use lookup tables to save computation time by precalculating some process into a table in which we already stored the result. In this case you are using the process to store the number of possible outcomes in an array. Basically you are building a lookup table for the dice outcome. Only the three inner loops are needed.
for (int k = 1; k <= 6; k++)
{
for (int i = 1; i <= 6; i ++)
{
for (int j = 1; j <= 6; j++)
{
arr[k + i + j-1] = arr[k + i + j-1] +1;
}
}
}
And this is what is happening:
dices index
i j k (i+j+k)
1 1 1 3
1 1 2 4
1 1 3 5
1 1 4 6
1 1 5 7
1 1 6 8
1 2 1 4
1 2 2 5
1 2 3 6
1 2 4 7
1 2 5 8
1 2 6 9
1 3 1 5
1 3 2 6
.
.
.
You are enumerating each possible outcome and then adding the spot in the array with the index generated. When the nested loops are done, you will have an array containing the desired information.

Interviewstreet Triplet [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
interviewstreet Triplet challenge
There is an integer array d which does not contain more than two elements of the same value. How many distinct ascending triples (d[i] < d[j] < d[k], i < j < k) are present?
Input format:
The first line contains an integer N denoting the number of elements in the array. This is followed by a single line containing N integers separated by a single space with no leading/trailing spaces
Output format:
A single integer that denotes the number of distinct ascending triples present in the array
Constraints:
N <= 10^5
Every element of the array is present at most twice
Every element of the array is a 32-bit positive integer
Sample input:
6
1 1 2 2 3 4
Sample output:
4
Explanation:
The distinct triplets are
(1,2,3)
(1,2,4)
(1,3,4)
(2,3,4)
EDIT: I assumed that the integers were ordered, which wasn't mentioned in your answer. With unordered integers, no optimization is possible, you'd have to use the brute force counting approach. If they are sorted, continue reading.
Thing is, you don't really need a lot of programming here. This is more of a mathematical problem.
First, it doesn't matter if there are 1, 2 or more occurences of an integer. The resulting triplets ave to be unique anyway. This reduces to merely counting how many different integers there are in the array. Name that variable s.
Then we merely apply following formula:
result = 0;
for(first_index = 0; first_index < s; first_index++) {
for(second_index = first_index + 1; second_index < s; second_index++) {
result += s - second_index - 1;
}
}
return result;
This can, however, be simplified. Now, if we reason about the values s - second_index - 1 takes for one outer loop, that's just the row of all integers from 0 to s - 2 reversed! Aren't we glad that there's a formula for its sum: where n is an integer, n * (n + 1) / 2 is the sum of the first n integers.
This means we can optimize our program to:
result = 0;
for(first_index = 0; first_index < s; first_index++) {
result += (s - 2 - first_index) * (s - 2 - first_index + 1) / 2;
}
Note that we can further simplify this to result = (x^3 - 3*x^2 + 2*x) / 6.

Categories