NOT ASKING FOR CODE TO ANSWER TO THIS SPECIFIC QUESTION, ASKING HOW TO APPROACH PROBLEM IN GENERAL
there's a question on codefights that asks to find all unique sums of two arrays, one size, the other quantity.
I'm using a cartesian product to determine all the possible permutations. This seems to be too much overhead. someone commented on the site that someone was able to do this in ONE for loop.
I'm looking for guidance on how to attack the problem from a cpu instead of memory approach.
int possibleSums(int[] coins, int[] quantity) {
var bitmaps = Enumerable.Range(1, Convert
.ToInt32(new string('1', coins.Length), 2))
.Select(bm => Convert.ToString(bm, 2).PadLeft(coins.Length,'0'));
var sums = coins
.Select((c, i) => new {
Index = i,
Coin = c,
Quantity = quantity[i]
})
.Select(cqi => new {
cqi.Coin,
cqi.Index,
cqi.Quantity,
CoinSums = Enumerable.Range(1, cqi.Quantity)
.Select(s => s * cqi.Coin)
});
var distinctSums = new HashSet<int>();
foreach (var map in bitmaps)
{
var coinsUsed = new List<IEnumerable<int>>();
for (var bitpos = 0; bitpos < map.Length; bitpos++)
{
if (map[bitpos] == '1')
{
coinsUsed.Add(sums.First(s => s.Index == bitpos).CoinSums);
}
}
var coinSums =
CartesianProduct(coinsUsed).Select(x => x.Sum());
foreach (var sum in coinSums)
{
if (!distinctSums.Contains(sum))
distinctSums.Add(sum);
}
}
return distinctSums.Count();
}
IEnumerable<IEnumerable<T>> CartesianProduct<T>( IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>()};
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] {item})
);
}