Given an Integer set, {x | 1 <= x <= n}. Consider a combination, something like 50C6 (select 6 from 50). Calculating the number of combinations and iterating over them (in sorted order) is easy.
For example, this does the trick:
public static void combo(int[] combo, int index, int f, int t) {
if (index >= combo.length) {
// display combination
// ...
return;
}
for (int i = f; i <= t - (combo.length - index) + 1; i++) {
combo[index] = i;
combo(combo, index + 1, i + 1, t);
}
}
For the above, calling combo(new int[]{0, 0, 0, 0}, 0, 1, 9) will list all the 9C4 combinations in sorted order, all 126 of them.
What I would like is the following. Given k, I'd like the algorithm to give the combination.
// Select r from c and return combination k.
public static int[] combo(int c, int r, int k) {
}
For example, combo(3,2,1) should return {1,2} and combo(3,2,3) should return {2,3} (assuming the first combination is 1 and not 0 - but that's trivial).
Doing this in O(nCr) is easy and takes little memory... Doing it in O(1) is also easy, but is requires lots of memory for larger combinations and requires pre-calculation. I don't know whether it's possible to do this in better time than O(nCr) without using a lookup table. Any confirmation/guidance would be appreciated.
Okay, I've worked it out and I am quite happy with the final result. The basic idea is as follows:
Let's say we want the k'th entry of nCr. Then, the number of combinations where we start with a 1 is (n-1)C(r-1) and a 2 is (n-2)C(r-2), etc. So, all you have to do is find out which digit needs to go at the first spot and then repeat the process for every one of the r spots.
For example, let's say we want the 30'th entry of 9C3. For 1, we have 8C2 = 28. That's not enough. For 2, 7C2 = 21. So, the first digit must be a 2 and the first entry that started with a 2 was entry 29. So now you simply repeat this process for the second and third entry.
The non-recursive solution is as follows:
public static int[] getCombo(int n, int r, int k) {
int[] result = new int[r];
int cur = 1;
int sum =0;
while (r > 0) {
int tot = c(n - cur, r - 1);
if (sum + tot < k) {
sum += tot;
cur++;
} else {
result[result.length - r] = cur++;
r--;
}
}
return result;
}
The function c() above, simply calculates "n select r".
I particularly like this as it is O(r).
So you can find the value of nCp by the equation n!/(p!*(n-p)!). So say you're solving 4C3 and you're looking for the kth combo. If the first value is a 1 then that means that you have 3C2 left which calculates to 3. So if k < 3 the first value is a 1. If not you go to 3C2 + 3C1 for the second value. And you recuse down the line. No sure if it's actually faster (the calculation of nCp) but it's an interesting way to think about the problem.
Related
I am trying to solve a problem on leetcode.com Ugly Number II.
problem: An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
example:
Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
This is my solution
class Solution {
public int nthUglyNumber(int n) {
int outputNumber = 6;
int temp = 1;
if (n < 7) {
return n;
}
int i = 7;
while (i != (n + 1)) {
outputNumber = outputNumber + 1;
temp = outputNumber;
while (temp % 5 == 0) {
temp = temp / 5;
}
while (temp % 2 == 0) {
temp = temp / 2;
}
while (temp % 3 == 0) {
temp = temp / 3;
}
if (temp == 1) {
i = i + 1;
}
}
return outputNumber;
}
}
this works for small numbers, but when the input is a big number, then I have Time Limit Exceeded
The question is how to optimize this code?
Thank you!
Hint: You're looking for numbers of the form 2a×3b×5c for non-negative integers a, b, c. Instead of looking for ugly numbers, wouldn't it be easier to just generate them?
I used two tricks to make it about twice as fast, but it's still far too slow. I suspect the check-all-integers-for-ugliness approach is hopeless, and you'll find faster approaches in the discussions on LeetCode.
class Solution {
public int nthUglyNumber(int n) {
for (int i = 1; true; i++)
if (1418776204833984375L % (i / (i & -i)) == 0)
if (--n == 0)
return i;
}
}
The two tricks:
i & -i extracts the lowest 1-bit, so dividing by that takes out every factor 2.
1418776204833984375 is 319×513. Every positive int with only factors 3 and 5 divides that, and every other positive int doesn't.
I think the easiest way is to just maintain a collection of ugly numbers that we will need to visit. We start with a collection containing just 1, and then at each step, we remove the lowest value, and add the values found by multiplying our lowest value by 2, by 3, and by 5. Since these may be duplicates (24 = 8 * 3 and 24 = 12 * 2) but we only want them once apiece, our collection should be a Set.
My Java is far too rusty, but here's a JavaScript implementation that you could use as pseudocode:
const ugly = (count) => {
const upcoming = new Set ([1])
const found = []
while (found .length < count) {
const next = Math .min (...upcoming .values ())
found .push (next)
upcoming .delete (next)
upcoming .add (2 * next)
upcoming .add (3 * next)
upcoming .add (5 * next)
}
return found
}
const uglies = ugly (1690) // This was the upper bound specified in the problem
const nthUglyNumber = (n) => uglies [n - 1]
console .log (nthUglyNumber (10))
console .log (nthUglyNumber (1690))
ugly finds the first count ugly numbers, returning them as an Array. Internally, it keeps two collections. upcoming is the ugly numbers we know we would eventually hit. found is an array of numbers we have actually reached, always taking the smallest of the upcoming values. When we select the next one, we remove it from upcoming and add to upcoming its 2-, 3-, and 5-multiples.
This could be modified to be our only function. But it's nice to call it once for our top value, and store the resulting array, as uglies. Then nthUglyNumber is a simple function that extracts the value at the correct index.
Here is the coin change problem from hackerrank(https://www.hackerrank.com/challenges/coin-change).
It asks to compute a total number of ways to make a change for N using coins of given denominations.
For example, there are four ways to make a change for 4 using coins of denominations 1, 2, and 3.
They are - {1,1,1,1}, {1,1,2}, {2,2}, {1,3}.
I've tried to implement a recursive solution using dynamic programming in java. My solution is based on the idea that, for each coin of given denominations, we recur to see if total can be reached by choosing the coin or not. If choosing the current coin results in the solution, we update a total number of ways. But the solution doesn't work.
Here's the implementation
public static long getWays(long n, long[] c) {
Map<String, Long> map = new HashMap<String, Long>();
return fun(n, c, 0, map);
}
public static long fun(long n, long[] c, int i, Map<String, Long> memo){
if(n == 0) return 1;
if(i >= c.length) return 0;
if(n < c[i]) return 0;
String key = n + "_" + i;
if(memo.containsKey(key)) return memo.get(key);
long ways = fun(n, c, i+1, memo) + fun(n-c[i], c, i, memo);
memo.put(key, ways);
return ways;
}
This gives me the wrong answer. For example, there are 5 ways to make a change for 10 using coins of {2, 5, 3, 6} but it returns 4 as the output.
where am I wrong?
At first glance, it looks like your solution will skip solutions if a coin higher than the remaining value is in a position before the i'th position in the array. Think about the case where n=5 and c=[10,5]. The answer there should be 1.
In your code, it would get to the if statement checking if n
if(n < c[i]) return 0;
And would return 0.
After about 7 hours in a row I really need some help , I need to return from recursion the amount of options that can be by setting numbers from 1 to chosen number(maximum number) , it's forbidden to use loops/arrays , only recursion , the numbers are all positive(more than 0) and goes only more positively , example : good one : {1,2} , bad one : {2,1}.
example :
n = 3 , max = 2
n : The numbers that should be in the row
, max : The maximum number that can be in the row.
{1,1,1}
{1,1,2}
{1,2,2}
{2,2,2}
from that example that should return 4 because there are 4 options of 3 numbers that their value is maximum 2.
another one:
n=2
max=3
{1,1}
{1,2}
{1,3}
{2,2}
{2,3}
{3,3}
from that example it should return 6 because there are 6 options.
Without prior knowledge, this would probably be a challenging question even for an experienced mathematician. It is the count of multisets, one of the fundamental building blocks in combinatorics. I'll explain my understanding of the idea for the recurrence relation in Wikipedia.
Typically k is used for the multiset cardinality (what your question refers to as n), while n is used as the cardinality of the set (not multiset) to choose from (the max in your question).
For f(n, k), the base cases are:
f(n, 0) = 1
one way to fill the empty multiset
And,
f(0, k) = 0
no ways to choose from an empty set
For the regular case, we consider the nth element (from the set of choices). We'd like to count all the combinations that include it and all those where it's missing. Counting all combinations without the nth element is easy: we have the same multiset counting function applied to k with one less choice:
f(n - 1, k)
Now to count the combinations that include at least one nth element, we imagine taking all the ways of choosing from n items (some of which will not include an nth element) but saving one place in each combination where we will place an nth element, so we end up with:
f(n, k - 1)
Putting it all together:
function f(n, k){
if (n == 0)
return 0;
if (k == 0)
return 1;
return f(n - 1, k) + f(n, k - 1);
}
console.log(f(2, 3));
console.log(f(3, 2));
Recursion can be hard to comprehend at first, but it is very clear to read once you get to know it. The downside is that recursion requires way more space than the basic for-loop (Space complexity of recursive function). For some problems it can be easier to first write the recursive version and afterwards write it as for-loop. Also, if space is not a problem, it helps to make your code clean (no for-loops!)
I made some basic recursion that gives the correct answer for at least the two examples you wrote down. It may be possible that I missed an edge case: maybe a good practise to write every function call and some (edgy) test cases.
public int recursiveWrapper(int n, int max) {
return recursive(n, max, 1, 1);
}
public int recursive(int n, int max, int lower, int current) {
// // for your convenience
// System.out.println("n:" + n + " max:" + max + " lowerbound:" + lower + " current:" + current);
// Base case
if (n <= 1 && lower == max) {
return 1;
}
// Recursive step
// Sequence complete, move to next column
if (current == max) {
// Make sure the lower bound does not go beyond the max. number
int updatedLower = (lower + 1 > max) ? lower : lower + 1;
return 1 + recursive(n - 1, max, updatedLower, updatedLower);
}
return 1 + recursive(n, max, lower, current + 1);
}
In short:
In the second example:
n=2
max=3
{1,1}
{1,2}
{1,3}
{2,2}
{2,3}
{3,3}
Note the pattern of the numbers that appears due to the rule that the numbers from left to right have to be equal or larger:
Second column: 1>2>3 > 2>3 > 3
First column: 1>1>1 > 2>2 > 3
The 'lower bound' parameter in the recursion is basically the lowest possible number the new 'sequence' can take (where each sequence is lower bound -> max number). The base case is then when the lower bound equals the upper bound and each column has done all it 'sequences'. Possibly not a very clear explanation - maybe it helps when you see what is printed out by the commented line in the code I copy pasted.
Note: Maybe it is possible to do the recursion with less parameters. Make sure to read a lot about recursion (for example wikipedia or your studybook?). Recursions makes it easier to find solutions and understand complex and abstract problems.
I have write some less efficient code due to time, try look at this, it will give you dir, i hope,
package com.exercise;
import java.util.Arrays;
public class Permutation {
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
private static void permutationOnInt(String prefix, String str, int max) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i <= n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
public static int[] return_Array(int length) {
int[] a = new int[length];
for (int i = 0; i < length; i++) {
a[i] = i + 1;
}
return a;
}
public static void main(String[] args) {
String fn = Arrays.toString(return_Array(3));
String apple = String.join(",", fn.replace("[", "").replace("]", "").replace(",", "").replaceAll("\\s+", ""));
permutationOnInt("", apple, 3);
}
}
After you get the result you can convert it back to the array.
Importent : This code is totally not optimized. I will post optimized later
Problem 31
In England the currency is made up of pound, £, and pence, p, and
there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p,
50p, £1 (100p) and £2 (200p). It is possible to make £2 in the
following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many
different ways can £2 be made using any number of coins?
static int[] nums = {200,100,50,20,10,5,2,1};
static int size = nums.length;
static HashMap<Integer,Integer> pivots = new HashMap<>();
public static int checkSum(HashMap<Integer,Integer> pivots){
int target = 200;
int sum = 0;
for(Integer key: pivots.keySet()){
int pivot = pivots.get(key);
sum += nums[pivot];
if(sum > target) return 1;
}
if(sum < target) return -1;
return 0;
}
public static void shift(HashMap<Integer,Integer> pivots, int pivot_node){
if(pivots.size() + nums[pivots.get(1)] == 201 && pivots.get(1) != 0){
int p_1_value = pivots.get(1); //this part checks whether the current node(which is the first node)
//has reached children of all 1.
//Which means it's time to shift the root node.
pivots.clear();
pivots.put(1 , p_1_value);
shift(pivots, 1);
return;
}
if(pivots.get(pivot_node) != size - 1) {
pivots.put(pivot_node, pivots.get(pivot_node) + 1);
}
else{
shift(pivots , pivot_node - 1);
}
}
public static void branch(HashMap<Integer,Integer> pivots){
pivots.put(pivots.size() + 1, pivots.get(pivots.size()));
}
public static int search(){
int bool = checkSum(pivots);
int n = 0;
int count = 0;
while(n < 25) {
count++;
if (bool == 0) {
n++; // if the sum is equal to 200, we shift the last
//pivot to the next lower number.
shift(pivots, pivots.size());
}else if (bool == -1) {
branch(pivots); //if the sum is less than 200, we make a new pivot with value of the last pivot.
}else if (bool == 1) {
shift(pivots, pivots.size()); //if the sum is greater than 200,
//we shift to the last pivot to the next lower number.
}
bool = checkSum(pivots);
}
return n;
}
public static void main(String[] args){
pivots.put(1,0);
int n = search();
System.out.print("\n\n------------\n\n"+ "n: " + n);
}
This is an algorithm that searches for combinations of a set that add up to a target. It's kind of like a depth first tree search without using a tree. Each pivot represents node on the "tree". The shift() method changes the value of the node to the next lower value. The branch() method creates a new node with the same value of the last node. The checkSum() method checks whether the sum of the pivots are <,= or > the target, 200.
The correct answer for the number of ways is supposed to be around 73000. But my algorithm only returns about 300 ways.
I have no idea why this happens because my algorithm should reach every single possible combination that equals 200.
This is a visualization of how my algorithm works:
Your search algorithm doesn't find all possible combinations of coins that make up £2 because you are only shifting the "last pivot" to the next lower number, when you should be considering the items before that last one too.
Your algorithm will find this combination:
100, 50, 20, 20, 5, 2, 2, 1
but not this:
100, 20, 20, 20, 10, 5, 2, 2, 1
The second combination does not have the value 50 in it, but your algorithm breaks down the coin values backwards to forwards only -i.e. it will never break down 50 until all the following "pivots" are 1. You can easily see that if you print your HashMap<Integer,Integer> pivots every time the counter n is incremented.
You could try to fix your code by amending it to shift() using not only the last pivot but all the distinct previous pivots too. However, doing so you will create a lot of duplicates, so you'll need to keep a list of the distinct found combinations.
Another way to solve problem 31 is by using Dynamic Programming. Dynamic programming is best when it comes to problems that can be broken down in smaller bits. For example the solution of the same problem but where
target = 2 can be used to solve the problem where target = 5, which can be used to solve the problem where target = 10 and so on.
Good luck!
Suppose, I have an unsorted array of overlapped ranges. Each range is just a pair of integers begin and end. Now I want to find if a given key belongs to at least one of the ranges. Probably, I have to know the ranges it belongs as well.
We can assume the ranges array takes ~1M and fits the memory. I am looking for an easy algorithm, which uses only standard JDK collections without any 3d-party libraries and special data structures, but works reasonably fast.
What would you suggest?
Sort the ranges numerically by a custom Comparator, then for each key k build a one-element range [k, k] and do a binary search for this range with a different Comparator.
The Comparator for searching's compare(x,y) should return
<0 if x.max < y.min
>0 if x.min > y.max
0 otherwise (its two range arguments overlap).
As noted by #Per, you need a different, stricter Comparator for sorting, but the first two clauses still hold.
This should work even if the ranges overlap, though you may want to merge overlapping ranges after sorting to speed up the search. The merging can be done in O(N) time.
This is in effect a static interval tree, i.e. one without O(lg N) insertion or deletion, in the same way that a sorted array can be considered a static binary search tree.
If you don't need to know which interval contains your point (EDIT: I guess you probably do, but I'll leave this answer for others with this question who don't), then
Preprocess the intervals by computing two arrays B and E. B is the values of begin in sorted order. E is the values of end in sorted order.
To query a point x, use binary search to find the least index i such that B[i] > x and the least index j such that E[j] ≥ x. The number of intervals [begin, end] containing x is i - j.
class Interval {
double begin, end;
}
class BeginComparator implements java.util.Comparator<Interval> {
public int compare(Interval o1, Interval o2) {
return Double.compare(o1.begin, o2.begin);
}
};
public class IntervalTree {
IntervalTree(Interval[] intervals_) {
intervals = intervals_.clone();
java.util.Arrays.sort(intervals, new BeginComparator());
maxEnd = new double[intervals.length];
initializeMaxEnd(0, intervals.length);
}
double initializeMaxEnd(int a, int b) {
if (a >= b) {
return Double.NEGATIVE_INFINITY;
}
int m = (a + b) >>> 1;
maxEnd[m] = initializeMaxEnd(a, m);
return Math.max(Math.max(maxEnd[m], intervals[m].end), initializeMaxEnd(m + 1, b));
}
void findContainingIntervals(double x, int a, int b, java.util.Collection<Interval> result) {
if (a >= b) {
return;
}
int m = (a + b) >>> 1;
Interval i = intervals[m];
if (x < i.begin) {
findContainingIntervals(x, a, m, result);
} else {
if (x <= i.end) {
result.add(i);
}
if (maxEnd[m] >= x) {
findContainingIntervals(x, a, m, result);
}
findContainingIntervals(x, m + 1, b, result);
}
}
java.util.Collection<Interval> findContainingIntervals(double x) {
java.util.Collection<Interval> result = new java.util.ArrayList<Interval>();
findContainingIntervals(x, 0, intervals.length, result);
return result;
}
Interval[] intervals;
double[] maxEnd;
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
Interval[] intervals = new Interval[10000];
for (int j = 0; j < intervals.length; j++) {
Interval i = new Interval();
do {
i.begin = r.nextDouble();
i.end = r.nextDouble();
} while (i.begin >= i.end);
intervals[j] = i;
}
IntervalTree it = new IntervalTree(intervals);
double x = r.nextDouble();
java.util.Collection<Interval> result = it.findContainingIntervals(x);
int count = 0;
for (Interval i : intervals) {
if (i.begin <= x && x <= i.end) {
count++;
}
}
System.out.println(result.size());
System.out.println(count);
}
}
I believe this is what you are looking for: http://en.wikipedia.org/wiki/Interval_tree
But check this simpler solution first to see if it fits your needs: Using java map for range searches
simple solution with O(n) complexity:
for(Range range: ranges){
if (key >= range.start && key <= range.end)
return range;
}
More clever algorithm can be applied if we know more information about ranges.
Is they sorted? Is they overlapped? and so on
Given just your specification, I would be inclined to order the ranges by size, with the widest ranges first (use a custom Comparator to facilitate this). Then simply iterate through them and return true as soon as you find a range that contains the key. Because we know nothing else about the data, of course the widest ranges are the most likely to contain a given key; searching them first could be a (small) optimization.
You could preprocess the list in other ways. For instance, you could exclude any ranges that are completely enclosed by other ranges. You could order by begin and early-exit as soon as you encounter a begin value greater than your key.