Related
A colleague of mine gave the following question to his C programming class which i found very interesting. It can easily be done in any programming language and immediately i thought wolfram.
The question is this:
The number 25 is a unique perfect square, If we increase each digit by one, it becomes 36 which is also a a perfect square!
write a program to find another set of numbers with the same qualities.
I am sure this can be easily done in mathematica.
Can someone explain how i can do this in mathematica. please note the reason of the question is just an excuse to get me into mathematica programming of which i know nothing.
thanks to all.
A more functional solution.
Table[x^2, {x, 1, 100}] // Select[IntegerQ[Sqrt[FromDigits[IntegerDigits[#] + 1]]] &]
How should the digit 9 be handled?
IntegerDigits[19]
(* {1, 9} *)
IntegerDigits[19] + 1
(* {2, 10} *)
FromDigits[IntegerDigits[19] + 1]
(* 30 *)
Should the +1 carry so the resulting number is 20 rather than 30?
You can easily expand this to any base and you only need to know how long the number is in a given base. What I mean is the following. Assume in base 10, the number 25. To check the premise, we need to add 11. But 11 is nothing more than:
25 + 11
= 25 + 10^1 + 10^0
= 25 + (10^2-1)/(10-1)
= 36 = 6^2
imagine now the number 72 × 72 = 5184, but represented in base 3 (518410 = 210100003). Doing now the computation in base 3, you get
21010000 + 11111111
= 21010000 + 3^7 + 3^6 + 3^5 + 3^4 + 3^3 + 3^2 + 3^1 + 3^0
= 21010000 + (3^8-1)/(3-1)
= 102121111 = 10102^2
where 1021211113 = 846410 = 9210 × 9210.
As you notice, all you need to do is add the number (bn - 1)/(b-1) to the number and check if it is a square. Here n, represents the total amount of digits of the number x in base b.
With a simple lookuptable, you do this in Mathematica as:
b = 10
x = Table[n^2, {n, 1, 1000}];
Select[x, MemberQ[x, # + (b^IntegerLength[#, b] - 1)/(b - 1)] &];
{25, 289, 2025, 13225, 100489, 198025, 319225, 466489}
and the full list for base 2 till base 10 is then:
Table[Select[x, MemberQ[x, # + (b^IntegerLength[#, b] - 1)/(b - 1)] &], {b, 2, 10}]
Instead of throwing you into the ocean, lets help you paddle around in the shallow end of the pool first.
n=1;
While[n<100,
d=IntegerDigits[n];(*get the list of digits making up n*)
newd=d+1;(*add one to every element of the list giving a new list*)
newn=FromDigits[newd];(*turn that new list of digits back into a number*)
If[IntegerQ[Sqrt[newn]],Print[{n,newn}]];
n++
]
That doesn't only look at square values of n, but it might give you the hint needed about how to increment the digits and test for a square result.
There are always at least a dozen different ways of doing anything in Mathematica and some of the culture revolves around making the programs as short, and potentially cryptic, as possible. You can start picking that up later. Simplicity seems better when getting started with a new language.
I hope you have fun.
find[from_, to_] := Module[{a, b, c, d, e},
a = Range[from, to];
b = a^2;
c = IntegerDigits[b];
(*Add 1's to the digits of the square,
except where the square contains a 9*)
d = MapThread[
If[MemberQ[#2, 9], Null,
#1 + FromDigits[ConstantArray[1, Length[#2]]]] &,
{b, c}];
(*Find the positions where the square roots are integers*)
e = Position[Sqrt[d], _?IntegerQ, {1}];
Extract[a, e]]
find[1, 1000000]
{5, 45, 115, 2205, 245795, 455645}
For example
Sqrt[45^2 + 1111]
56
and
Sqrt[455645^2 + 111111111111]
564556
I'm working on a program in Visual Basic that takes user input as an integer from 1 to 99 and then tells the use how many quarters, dimes, Nickles, and pennies you need to supplement for that amount. My problem is completely symantical, and my algorithm isn't working like I thought it would. Here is the code that does the actual math, where the variables used are already declared
Select Case Input
Case 25 to 99
numQuarters = Input / 25
remainder = Input Mod 25
Select Case remainder
Case 10 to 24
numDimes = remainder / 10
remainder = remainder mod 10
numNickles = remainder / 5
remainder = remainder mod 5
numPennies = remainder
I'm going to stop there, because that's the only part of the code that's giving me trouble. When I enter a number from 88 to 99 (which is handled by that part of the code) the numbers come out strange. For example, 88 gives me 4 quarters, 1 dime, 1 Nickle, and 3 pennies. I'm not quite sure what's happening, but if someone could help me, I would appreciate it.
I reckon your problem was that it was storing the fractional part of the division, when it should be dropping it and keeping only whole multiples as the fractional portion of each coin is reflected in the remainder.
So after each division, truncate it. E.g.:
numQuarters = Int(Input / 25)
remainder = Input Mod 25
'or since you aren't working with fractional currencies you could use integral division operator '\':
numQuarters = Input \ 25
With 88 as the input it will, after these lines, have numQuarters = 3 and remainder = 18
Anyway, pehaps a more flexible way that doesn't rely on hard-coded orders of precedence and can handle whatever units you like (cents, fractional dollars, whatever) is like:
Sub exampleUsage()
Dim denominations, change
Dim i As Long, txt
'basic UK coins, replace with whatever
'you can of course use pence as the unit, rather than pounds
denominations = Array(1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01)
change = ChaChing(3.78, denominations)
For i = 0 To UBound(denominations)
txt = txt & Format(denominations(i), "£0.00") & " x " & change(i) & " = " & Format(denominations(i) * change(i), "£0.00") & vbCrLf
Next i
MsgBox (txt)
End Sub
'denominations is a Vector of valid denominations of the amount
'the return is a Vector, corresponding to denominations, of the amount of each denomination
Public Function ChaChing(ByVal money As Double, denominations)
Dim change, i As Long
ReDim change(LBound(denominations) To UBound(denominations))
For i = LBound(denominations) To UBound(denominations)
If money = 0 Then Exit For 'short-circuit
change(i) = Int(money / denominations(i))
money = money - change(i) * denominations(i)
Next i
ChaChing = change
End Function
So I'm creating a Activation class for a VB6 project and I've run into a brain fart. I've designed how I want to generate the Serial Number for this particular product in a following way.
XXXX-XXXX-XXXX-XXXX
Each group of numbers would be representative of data that I can read if I'm aware of the matching document that allows me to understand the codes with the group of digits. So for instance the first group may represent the month that the product was sold to a customer. But I can't have all the serial numbers in January all start with the same four digits so there's some internal math that needs to be done to calculate this value. What I've landed on is this:
A B C D = digits in the first group of the serial number
(A + B) - (C + D) = #
Now # would relate to a table of Hex values that would then represent the month the product was sold. Something like...
1 - January
2 - February
3 - March
....
B - November
C - December
My question lies here - if I know I need the total to equal B(11) then how exactly can I code backwards to generate (A + B) - (C + D) = B(11)?? It's a pretty simple equation, I know - but something I've just ran into and can't seem to get started in the right direction. I'm not asking for a full work-up of code but just a push. If you have a full solution available and want to share I'm always open to learning a bit more.
I am coding in VB6 but VB.NET, C#, C++ solutions could work as well since I can just port those over relatively easily. The community help is always greatly appreciated!
There's no single solution (you have one equation with four variables). You have to pick some random numbers. Here's one that works (in Python, but you get the point):
from random import randint
X = 11 # the one you're looking for
A_plus_B = randint(X, 30)
A = randint(max(A_plus_B - 15, 0), min(A_plus_B, 15))
B = A_plus_B - A
C_plus_D = A_plus_B - X
C = randint(max(C_plus_D - 15, 0), min(C_plus_D, 15))
D = C_plus_D - C
I assume you allow hexadecimal digits; if you just want 0 to 9, replace 15 by 9 and 30 by 18.
OK - pen and paper is always the solution... so here goes...
Attempting to find what values should be for (A + B) - (C + D) to equal a certain number called X. First I know that I want HEX values so that limits me to 0-F or 0-15. From there I need a better starting place so I'll generate a random number that will represent the total of (A + B), we'll call this Y, but not be lower than value X. Then subtract from that number Y value of X to determine that value that will represent (C + D), which we'll call Z. Use similar logic to break down Y and Z into two numbers each that can represent (A + B) = Y and (C + D) = Z. After it's all said and done I should have a good randomization of creating 4 numbers that when plugged into my equation will return a suitable result.
Just had to get past the brain fart.
This may seem a little hackish, and it may not take you where you're trying to go. However it should produce a wider range of values for your key strings:
Option Explicit
Private Function MonthString(ByVal MonthNum As Integer) As String
'MonthNum: January=1, ... December=12. Altered to base 0
'value for use internally.
Dim lngdigits As Long
MonthNum = MonthNum - 1
lngdigits = (Rnd() * &H10000) - MonthNum
MonthString = Right$("000" & Hex$(lngdigits + (MonthNum - lngdigits Mod 12)), 4)
End Function
Private Function MonthRecov(ByVal MonthString As String) As Integer
'Value returned is base 1, i.e. 1=January.
MonthRecov = CInt(CLng("&H" & MonthString) Mod 12) + 1
End Function
Private Sub Form_Load()
Dim intMonth As Integer
Dim strMonth As String
Dim intMonthRecov As Integer
Dim J As Integer
Randomize
For intMonth = 1 To 12
For J = 1 To 2
strMonth = MonthString(intMonth)
intMonthRecov = MonthRecov(strMonth)
Debug.Print intMonth, strMonth, intMonthRecov, Hex$(intMonthRecov)
Next
Next
End Sub
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I recently posted one of my favourite interview whiteboard coding questions in "What's your more controversial programming opinion", which is to write a function that computes Pi using the Leibniz formula.
It can be approached in a number of different ways, and the exit condition takes a bit of thought, so I thought it might make an interesting code golf question. Shortest code wins!
Given that Pi can be estimated using the function 4 * (1 - 1/3 + 1/5 - 1/7 + ...) with more terms giving greater accuracy, write a function that calculates Pi to within 0.00001.
Edit: 3 Jan 2008
As suggested in the comments I changed the exit condition to be within 0.00001 as that's what I really meant (an accuracy 5 decimal places is much harder due to rounding and so I wouldn't want to ask that in an interview, whereas within 0.00001 is an easier to understand and implement exit condition).
Also, to answer the comments, I guess my intention was that the solution should compute the number of iterations, or check when it had done enough, but there's nothing to prevent you from pre-computing the number of iterations and using that number. I really asked the question out of interest to see what people would come up with.
J, 14 chars
4*-/%>:+:i.1e6
Explanation
1e6 is number 1 followed by 6 zeroes (1000000).
i.y generates the first y non negative numbers.
+: is a function that doubles each element in the list argument.
>: is a function that increments by one each element in the list argument.
So, the expression >:+:i.1e6 generates the first one million odd numbers:
1 3 5 7 ...
% is the reciprocal operator (numerator "1" can be omitted).
-/ does an alternate sum of each element in the list argument.
So, the expression -/%>:+:i.1e6 generates the alternate sum of the reciprocals of the first one million odd numbers:
1 - 1/3 + 1/5 - 1/7 + ...
4* is multiplication by four. If you multiply by four the previous sum, you have π.
That's it! J is a powerful language for mathematics.
Edit: since generating 9! (362880) terms for the alternate sum is sufficient to have 5 decimal digit accuracy, and since the Leibniz formula can be written also this way:
4 - 4/3 + 4/5 - 4/7 + ...
...you can write a shorter, 12 chars version of the program:
-/4%>:+:i.9!
Language: Brainfuck, Char count: 51/59
Does this count? =]
Because there are no floating-point numbers in Brainfuck, it was pretty difficult to get the divisions working properly. Grr.
Without newline (51):
+++++++[>+++++++<-]>++.-----.+++.+++.---.++++.++++.
With newline (59):
+++++++[>+++++++>+<<-]>++.-----.+++.+++.---.++++.++++.>+++.
Perl
26 chars
26 just the function, 27 to compute, 31 to print. From the comments to this answer.
sub _{$-++<1e6&&4/$-++-&_} # just the sub
sub _{$-++<1e6&&4/$-++-&_}_ # compute
sub _{$-++<1e6&&4/$-++-&_}say _ # print
28 chars
28 just computing, 34 to print. From the comments. Note that this version cannot use 'say'.
$.=.5;$\=2/$.++-$\for 1..1e6 # no print
$.=.5;$\=2/$.++-$\for$...1e6;print # do print, with bonus obfuscation
36 chars
36 just computing, 42 to print. Hudson's take at dreeves's rearrangement, from the comments.
$/++;$\+=8/$//($/+2),$/+=4for$/..1e6
$/++;$\+=8/$//($/+2),$/+=4for$/..1e6;print
About the iteration count: as far as my math memories go, 400000 is provably enough to be accurate to 0.00001. But a million (or as low as 8e5) actually makes the decimal expansion actually match 5 fractional places, and it's the same character count so I kept that.
Ruby, 33 characters
(0..1e6).inject{|a,b|2/(0.5-b)-a}
Another C# version:
(60 characters)
4*Enumerable.Range(0, 500000).Sum(x => Math.Pow(-1, x)/(2*x + 1)); // = 3,14159
52 chars in Python:
print 4*sum(((-1.)**i/(2*i+1)for i in xrange(5**8)))
(51 dropping the 'x' from xrange.)
36 chars in Octave (or Matlab):
l=0:5^8;disp((-1).^l*(4./(2.*l+1))')
(execute "format long;" to show all the significant digits.) Omitting 'disp' we reach 30 chars:
octave:5> l=0:5^8;(-1).^l*(4./(2.*l+1))'
ans = 3.14159009359631
Oracle SQL 73 chars
select -4*sum(power(-1,level)/(level*2-1)) from dual connect by level<1e6
Language: C, Char count: 71
float p;main(i){for(i=1;1E6/i>5;i+=2)p-=(i%4-2)*4./i;printf("%g\n",p);}
Language: C99, Char count: 97 (including required newline)
#include <stdio.h>
float p;int main(){for(int i=1;1E6/i>5;i+=2)p-=(i%4-2)*4./i;printf("%g\n",p);}
I should note that the above versions (which are the same) keep track of whether an extra iteration would affect the result at all. Thus, it performs a minimum number of operations. To add more digits, replace 1E6 with 1E(num_digits+1) or 4E5 with 4E(num_digits) (depending on the version). For the full programs, %g may need to be replaced. float may need to be changed to double as well.
Language: C, Char count: 67 (see notes)
double p,i=1;main(){for(;i<1E6;i+=4)p+=8/i/(i+2);printf("%g\n",p);}
This version uses a modified version of posted algorithm, as used by some other answers. Also, it is not as clean/efficient as the first two solutions, as it forces 100 000 iterations instead of detecting when iterations become meaningless.
Language: C, Char count: 24 (cheating)
main(){puts("3.14159");}
Doesn't work with digit counts > 6, though.
Haskell
I got it down to 34 characters:
foldl subtract 4$map(4/)[3,5..9^6]
This expression yields 3.141596416935556 when evaluated.
Edit: here's a somewhat shorter version (at 33 characters) that uses foldl1 instead of foldl:
foldl1 subtract$map(4/)[1,3..9^6]
Edit 2: 9^6 instead of 10^6. One has to be economical ;)
Edit 3: Replaced with foldl' and foldl1' with foldl and foldl1 respectively—as a result of Edit 2, it no longer overflows. Thanks to ShreevatsaR for noticing this.
23 chars in MATLAB:
a=1e6;sum(4./(1-a:4:a))
F#:
Attempt #1:
let pi = 3.14159
Cheating? No, its winning with style!
Attempt #2:
let pi =
seq { 0 .. 100 }
|> Seq.map (fun x -> float x)
|> Seq.fold (fun x y -> x + (Math.Pow(-1.0, y)/(2.0 * y + 1.0))) 0.0
|> (fun x -> x * 4.0)
Its not as compact as it could possibly get, but pretty idiomatic F#.
common lisp, 55 chars.
(loop for i from 1 upto 4e5 by 4 sum (/ 8d0 i (+ i 2)))
Mathematica, 27 chars (arguably as low as 26, or as high as 33)
NSum[8/i/(i+2),{i,1,9^9,4}]
If you remove the initial "N" then it returns the answer as a (huge) fraction.
If it's cheating that Mathematica doesn't need a print statement to output its result then prepend "Print#" for a total of 33 chars.
NB:
If it's cheating to hardcode the number of terms, then I don't think any answer has yet gotten this right. Checking when the current term is below some threshold is no better than hardcoding the number of terms. Just because the current term is only changing the 6th or 7th digit doesn't mean that the sum of enough subsequent terms won't change the 5th digit.
Using the formula for the error term in an alternating series (and thus the necessary number of iterations to achieve the desired accuracy is not hard coded into the program):
public static void Main(string[] args) {
double tolerance = 0.000001;
double piApproximation = LeibnizPi(tolerance);
Console.WriteLine(piApproximation);
}
private static double LeibnizPi(double tolerance) {
double quarterPiApproximation = 0;
int index = 1;
double term;
int sign = 1;
do {
term = 1.0 / (2 * index - 1);
quarterPiApproximation += ((double)sign) * term;
index++;
sign = -sign;
} while (term > tolerance);
return 4 * quarterPiApproximation;
}
C#:
public static double Pi()
{
double pi = 0;
double sign = 1;
for (int i = 1; i < 500002; i += 2)
{
pi += sign / i;
sign = -sign;
}
return 4 * pi;
}
Perl :
$i+=($_&1?4:-4)/($_*2-1)for 1..1e6;print$i
for a total of 42 chars.
Ruby, 41 chars (using irb):
s=0;(3..3e6).step(4){|i|s+=8.0/i/(i-2)};s
Or this slightly longer, non-irb version:
s=0;(3..3e6).step(4){|i|s+=8.0/i/(i-2)};p s
This is a modified Leibniz:
Combine pairs of terms. This gives you 2/3 + 2/35 + 2/99 + ...
Pi becomes 8 * (1/(1 * 3) + 1/(5 * 7) + 1/(9 * 11) + ...)
F# (Interactive Mode) (59 Chars)
{0.0..1E6}|>Seq.fold(fun a x->a+ -1.**x/(2.*x+1.))0.|>(*)4.
(Yields a warning but omits the casts)
Here's a solution in MUMPS.
pi(N)
N X,I
S X=1 F I=3:4:N-2 S X=X-(1/I)+(1/(I+2))
Q 4*X
Parameter N indicates how many repeated fractions to use. That is, if you pass in 5 it will evaluate 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11)
Some empirical testing showed that N=272241 is the lowest value that gives a correct value of 3.14159 when truncated to 5 decimal points. You have to go to N=852365 to get a value that rounds to 3.14159.
C# using iterator block:
static IEnumerable<double> Pi()
{
double i = 4, j = 1, k = 4;
for (;;)
{
yield return k;
k += (i *= -1) / (j += 2);
}
}
For the record, this Scheme implementation has 95 characters ignoring unnecessary whitespace.
(define (f)
(define (p a b)
(if (> a b)
0
(+ (/ 1.0 (* a (+ a 2))) (p (+ a 4) b))))
(* 8 (p 1 1e6)))
Javascript:
a=0,b=-1,d=-4,c=1e6;while(c--)a+=(d=-d)/(b+=2)
In javascript. 51 characters. Obviously not going to win but eh. :P
Edit -- updated to be 46 characters now, thanks to Strager. :)
UPDATE (March 30 2010)
A faster (precise only to 5 decimal places) 43 character version by David Murdoch
for(a=0,b=1,d=4,c=~4e5;++c;d=-d)a-=d/(b-=2)
Here's a recursive answer using C#. It will only work using the x64 JIT in Release mode because that's the only JIT that applies tail-call optimisation, and as the series converges so slowly it will result in a StackOverflowException without it.
It would be nice to have the IteratePi function as an anonymous lambda, but as it's self-recursive we'd have to start doing all manner of horrible things with Y-combinators so I've left it as a separate function.
public static double CalculatePi()
{
return IteratePi(0.0, 1.0, true);
}
private static double IteratePi(double result, double denom, bool add)
{
var term = 4.0 / denom;
if (term < 0.00001) return result;
var next = add ? result + term : result - term;
return IteratePi(next, denom + 2.0, !add);
}
Most of the current answers assume that they'll get 5 digits accuracy within some number of iterations and this number is hardcoded into the program. My understanding of the question was that the program itself is supposed to figure out when it's got an answer accurate to 5 digits and stop there. On that assumption here's my C# solution. I haven't bothered to minimise the number of characters since there's no way it can compete with some of the answers already out there, so I thought I'd make it readable instead. :)
private static double GetPi()
{
double acc = 1, sign = -1, lastCheck = 0;
for (double div = 3; ; div += 2, sign *= -1)
{
acc += sign / div;
double currPi = acc * 4;
double currCheck = Math.Round(currPi, 5);
if (currCheck == lastCheck)
return currPi;
lastCheck = currCheck;
}
}
Language: C99 (implicit return 0), Char count: 99 (95 + 4 required spaces)
exit condition depends on current value, not on a fixed count
#include <stdio.h>
float p, s=4, d=1;
int main(void) {
for (; 4/d > 1E-5; d += 2)
p -= (s = -s) / d;
printf("%g\n", p);
}
compacted version
#include<stdio.h>
float
p,s=4,d=1;int
main(void){for(;4/d>1E-5;d+=2)p-=(s=-s)/d;printf("%g\n",p);}
Language: dc, Char count: 35
dc -e '9k0 1[d4r/r2+sar-lad274899>b]dsbxrp'
Ruby:
irb(main):031:0> 4*(1..10000).inject {|s,x| s+(-1)**(x+1)*1.0/(2*x-1)}
=> 3.14149265359003
64 chars in AWK:
~# awk 'BEGIN {p=1;for(i=3;i<10^6;i+=4){p=p-1/i+1/(i+2)}print p*4}'
3.14159
C# cheating - 50 chars:
static single Pi(){
return Math.Round(Math.PI, 5));
}
It only says "taking into account the formula write a function..." it doesn't say reproduce the formula programmatically :) Think outside the box...
C# LINQ - 78 chars:
static double pi = 4 * Enumerable.Range(0, 1000000)
.Sum(n => Math.Pow(-1, n) / (2 * n + 1));
C# Alternate LINQ - 94 chars:
static double pi = return 4 * (from n in Enumerable.Range(0, 1000000)
select Math.Pow(-1, n) / (2 * n + 1)).Sum();
And finally - this takes the previously mentioned algorithm and condenses it mathematically so you don't have to worry about keep changing signs.
C# longhand - 89 chars (not counting unrequired spaces):
static double pi()
{
var t = 0D;
for (int n = 0; n < 1e6; t += Math.Pow(-1, n) / (2 * n + 1), n++) ;
return 4 * t;
}
#!/usr/bin/env python
from math import *
denom = 1.0
imm = 0.0
sgn = 1
it = 0
for i in xrange(0, int(1e6)):
imm += (sgn*1/denom)
denom += 2
sgn *= -1
print str(4*imm)
Not sure how best to explain it, other than using an example...
Imagine having a client with 10 outstanding invoices, and one day they provide you with a cheque, but do not tell you which invoices it's for.
What would be the best way to return all the possible combination of values which can produce the required total?
My current thinking is a kind of brute force method, which involves using a self-calling function that runs though all the possibilities (see current version).
For example, with 3 numbers, there are 15 ways to add them together:
A
A + B
A + B + C
A + C
A + C + B
B
B + A
B + A + C
B + C
B + C + A
C
C + A
C + A + B
C + B
C + B + A
Which, if you remove the duplicates, give you 7 unique ways to add them together:
A
A + B
A + B + C
A + C
B
B + C
C
However, this kind of falls apart after you have:
15 numbers (32,767 possibilities / ~2 seconds to calculate)
16 numbers (65,535 possibilities / ~6 seconds to calculate)
17 numbers (131,071 possibilities / ~9 seconds to calculate)
18 numbers (262,143 possibilities / ~20 seconds to calculate)
Where, I would like this function to handle at least 100 numbers.
So, any ideas on how to improve it? (in any language)
This is a pretty common variation of the subset sum problem, and it is indeed quite hard. The section on the Pseudo-polynomial time dynamic programming solution on the page linked is what you're after.
This is strictly for the number of possibilities and does not consider overlap. I am unsure what you want.
Consider the states that any single value could be at one time - it could either be included or excluded. That is two different states so the number of different states for all n items will be 2^n. However there is one state that is not wanted; that state is when none of the numbers are included.
And thus, for any n numbers, the number of combinations is equal to 2^n-1.
def setNumbers(n): return 2**n-1
print(setNumbers(15))
These findings are very closely related to combinations and permutations.
Instead, though, I think you may be after telling whether given a set of values any combination of them sum to a value k. For this Bill the Lizard pointed you in the right direction.
Following from that, and bearing in mind I haven't read the whole Wikipedia article, I propose this algorithm in Python:
def combs(arr):
r = set()
for i in range(len(arr)):
v = arr[i]
new = set()
new.add(v)
for a in r: new.add(a+v)
r |= new
return r
def subsetSum(arr, val):
middle = len(arr)//2
seta = combs(arr[:middle])
setb = combs(arr[middle:])
for a in seta:
if (val-a) in setb:
return True
return False
print(subsetSum([2, 3, 5, 8, 9], 8))
Basically the algorithm works as this:
Splits the list into 2 lists of approximately half the length. [O(n)]
Finds the set of subset sums. [O(2n/2 n)]
Loops through the first set of up to 2floor(n/2)-1 values seeing if the another value in the second set would total to k. [O(2n/2 n)]
So I think overall it runs in O(2n/2 n) - still pretty slow but much better.
Sounds like a bin packing problem. Those are NP-complete, i.e. it's nearly impossible to find a perfect solution for large problem sets. But you can get pretty close using heuristics, which are probably applicable to your problem even if it's not strictly a bin packing problem.
This is a variant on a similar problem.
But you can solve this by creating a counter with n bits. Where n is the amount of numbers. Then you count from 000 to 111 (n 1's) and for each number a 1 is equivalent to an available number:
001 = A
010 = B
011 = A+B
100 = C
101 = A+C
110 = B+C
111 = A+B+C
(But that was not the question, ah well I leave it as a target).
It's not strictly a bin packing problem. It's a what combination of values could have produced another value.
It's more like the change making problem, which has a bunch of papers detailing how to solve it. Google pointed me here: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.57.3243
I don't know how often it would work in practice as there are many exceptions to this oversimplified case, but here's a thought:
In a perfect world, the invoices are going to be paid up to a certain point. People will pay A, or A+B, or A+B+C, but not A+C - if they've received invoice C then they've received invoice B already. In the perfect world the problem is not to find to a combination, it's to find a point along a line.
Rather than brute forcing every combination of invoice totals, you could iterate through the outstanding invoices in order of date issued, and simply add each invoice amount to a running total which you compare with the target figure.
Back in the real world, it's a trivially quick check you can do before launching into the heavy number-crunching, or chasing them up. Any hits it gets are a bonus :)
Here is an optimized Object-Oriented version of the exact integer solution to the Subset Sums problem(Horowitz, Sahni 1974). On my laptop (which is nothing special) this vb.net Class solves 1900 subset sums a second (for 20 items):
Option Explicit On
Public Class SubsetSum
'Class to solve exact integer Subset Sum problems'
''
' 06-sep-09 RBarryYoung Created.'
Dim Power2() As Integer = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32764}
Public ForceMatch As Boolean
Public watch As New Stopwatch
Public w0 As Integer, w1 As Integer, w1a As Integer, w2 As Integer, w3 As Integer, w4 As Integer
Public Function SolveMany(ByVal ItemCount As Integer, ByVal Range As Integer, ByVal Iterations As Integer) As Integer
' Solve many subset sum problems in sequence.'
''
' 06-sep-09 RBarryYoung Created.'
Dim TotalFound As Integer
Dim Items() As Integer
ReDim Items(ItemCount - 1)
'First create our list of selectable items:'
Randomize()
For item As Integer = 0 To Items.GetUpperBound(0)
Items(item) = Rnd() * Range
Next
For iteration As Integer = 1 To Iterations
Dim TargetSum As Integer
If ForceMatch Then
'Use a random value but make sure that it can be matched:'
' First, make a random bitmask to use:'
Dim bits As Integer = Rnd() * (2 ^ (Items.GetUpperBound(0) + 1) - 1)
' Now enumerate the bits and match them to the Items:'
Dim sum As Integer = 0
For b As Integer = 0 To Items.GetUpperBound(0)
'build the sum from the corresponding items:'
If b < 16 Then
If Power2(b) = (bits And Power2(b)) Then
sum = sum + Items(b)
End If
Else
If Power2(b - 15) * Power2(15) = (bits And (Power2(b - 15) * Power2(15))) Then
sum = sum + Items(b)
End If
End If
Next
TargetSum = sum
Else
'Use a completely random Target Sum (low chance of matching): (Range / 2^ItemCount)'
TargetSum = ((Rnd() * Range / 4) + Range * (3.0 / 8.0)) * ItemCount
End If
'Now see if there is a match'
If SolveOne(TargetSum, ItemCount, Range, Items) Then TotalFound += 1
Next
Return TotalFound
End Function
Public Function SolveOne(ByVal TargetSum As Integer, ByVal ItemCount As Integer _
, ByVal Range As Integer, ByRef Items() As Integer) As Boolean
' Solve a single Subset Sum problem: determine if the TargetSum can be made from'
'the integer items.'
'first split the items into two half-lists: [O(n)]'
Dim H1() As Integer, H2() As Integer
Dim hu1 As Integer, hu2 As Integer
If ItemCount Mod 2 = 0 Then
'even is easy:'
hu1 = (ItemCount / 2) - 1 : hu2 = (ItemCount / 2) - 1
ReDim H1((ItemCount / 2) - 1), H2((ItemCount / 2) - 1)
Else
'odd is a little harder, give the first half the extra item:'
hu1 = ((ItemCount + 1) / 2) - 1 : hu2 = ((ItemCount - 1) / 2) - 1
ReDim H1(hu1), H2(hu2)
End If
For i As Integer = 0 To ItemCount - 1 Step 2
H1(i / 2) = Items(i)
'make sure that H2 doesnt run over on the last item of an odd-numbered list:'
If (i + 1) <= ItemCount - 1 Then
H2(i / 2) = Items(i + 1)
End If
Next
'Now generate all of the sums for each half-list: [O( 2^(n/2) * n )] **(this is the slowest step)'
Dim S1() As Integer, S2() As Integer
Dim sum1 As Integer, sum2 As Integer
Dim su1 As Integer = 2 ^ (hu1 + 1) - 1, su2 As Integer = 2 ^ (hu2 + 1) - 1
ReDim S1(su1), S2(su2)
For i As Integer = 0 To su1
' Use the binary bitmask of our enumerator(i) to select items to use in our candidate sums:'
sum1 = 0 : sum2 = 0
For b As Integer = 0 To hu1
If 0 < (i And Power2(b)) Then
sum1 += H1(b)
If i <= su2 Then sum2 += H2(b)
End If
Next
S1(i) = sum1
If i <= su2 Then S2(i) = sum2
Next
'Sort both lists: [O( 2^(n/2) * n )] **(this is the 2nd slowest step)'
Array.Sort(S1)
Array.Sort(S2)
' Start the first half-sums from lowest to highest,'
'and the second half sums from highest to lowest.'
Dim i1 As Integer = 0, i2 As Integer = su2
' Now do a merge-match on the lists (but reversing S2) and looking to '
'match their sum to the target sum: [O( 2^(n/2) )]'
Dim sum As Integer
Do While i1 <= su1 And i2 >= 0
sum = S1(i1) + S2(i2)
If sum < TargetSum Then
'if the Sum is too low, then we need to increase the ascending side (S1):'
i1 += 1
ElseIf sum > TargetSum Then
'if the Sum is too high, then we need to decrease the descending side (S2):'
i2 -= 1
Else
'Sums match:'
Return True
End If
Loop
'if we got here, then there are no matches to the TargetSum'
Return False
End Function
End Class
Here is the Forms code to go along with it:
Public Class frmSubsetSum
Dim ssm As New SubsetSum
Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
Dim Total As Integer
Dim datStart As Date, datEnd As Date
Dim Iterations As Integer, Range As Integer, NumberCount As Integer
Iterations = CInt(txtIterations.Text)
Range = CInt(txtRange.Text)
NumberCount = CInt(txtNumberCount.Text)
ssm.ForceMatch = chkForceMatch.Checked
datStart = Now
Total = ssm.SolveMany(NumberCount, Range, Iterations)
datEnd = Now()
lblStart.Text = datStart.TimeOfDay.ToString
lblEnd.Text = datEnd.TimeOfDay.ToString
lblRate.Text = Format(Iterations / (datEnd - datStart).TotalMilliseconds * 1000, "####0.0")
ListBox1.Items.Insert(0, "Found " & Total.ToString & " Matches out of " & Iterations.ToString & " tries.")
ListBox1.Items.Insert(1, "Tics 0:" & ssm.w0 _
& " 1:" & Format(ssm.w1 - ssm.w0, "###,###,##0") _
& " 1a:" & Format(ssm.w1a - ssm.w1, "###,###,##0") _
& " 2:" & Format(ssm.w2 - ssm.w1a, "###,###,##0") _
& " 3:" & Format(ssm.w3 - ssm.w2, "###,###,##0") _
& " 4:" & Format(ssm.w4 - ssm.w3, "###,###,##0") _
& ", tics/sec = " & Stopwatch.Frequency)
End Sub
End Class
Let me know if you have any questions.
For the record, here is some fairly simple Java code that uses recursion to solve this problem. It is optimised for simplicity rather than performance, although with 100 elements it seems to be quite fast. With 1000 elements it takes dramatically longer, so if you are processing larger amounts of data you could better use a more sophisticated algorithm.
public static List<Double> getMatchingAmounts(Double goal, List<Double> amounts) {
List<Double> remaining = new ArrayList<Double>(amounts);
for (final Double amount : amounts) {
if (amount > goal) {
continue;
} else if (amount.equals(goal)) {
return new ArrayList<Double>(){{ add(amount); }};
}
remaining.remove(amount);
List<Double> matchingAmounts = getMatchingAmounts(goal - amount, remaining);
if (matchingAmounts != null) {
matchingAmounts.add(amount);
return matchingAmounts;
}
}
return null;
}