Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Ever wondered how many squares there are in a grid of squares?
- //How about rectangles?
- //Inspired by this image: http://krexy.com/how-many-squares
- //Found in many places online.
- //Much thanks to LinqPad for providing such a nice dev environment.
- //Basic Formula's - simple programming
- Func<int,int> boxQuery = d =>
- (from x in Enumerable.Range(0,d)
- select (d-x) * (d-x)).Sum();
- Func<int,int> rectQuery = d =>
- (from x in Enumerable.Range(0,d)
- from y in Enumerable.Range(0,d)
- select (d-x) * (d-y)).Sum();
- (boxQuery(4) + boxQuery(2)*2).Dump(); //40 - the answer to the given image.
- (rectQuery(4) + rectQuery(2)*2).Dump(); //118 - the same image, but including rectangles.
- //Pure mathematical representations [thanks to WolframAlpha for providing basic formula]
- Func<int,int> boxWolfPure = d => {d++; return ((2 * d)-1) *(d*(d-1))/6 ;};
- Func<int,int> rectWolfPure = d => {d++; return ((d-1) * (d*d*d - d*d))/4;};
- //Mixed math/programming - makes use of state [all d's after and inc ++d are actually (d+1)]
- //Probably an abuse of code.
- //Func<int,int> boxWolf = d => d*++d*(2*d-1)/6;
- Func<int,int> boxWolf = d => d*(d +++d)*d/6;
- Func<int,int> rectWolf = d => d*d*++d*d/4;
- for (int i=0; i<100; i++) (boxQuery(i) + " " + boxWolf(i) + " " + rectQuery(i) + " " + rectWolf(i)).Dump();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement