Advertisement
NPSF3000

++d +++d

Feb 21st, 2013
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. //Ever wondered how many squares there are in a grid of squares?
  2. //How about rectangles?
  3. //Inspired by this image:  http://krexy.com/how-many-squares
  4. //Found in many places online.
  5.  
  6. //Much thanks to LinqPad for providing such a nice dev environment.
  7.  
  8. //Basic Formula's - simple programming
  9. Func<int,int> boxQuery = d =>
  10.     (from x in Enumerable.Range(0,d)
  11.     select (d-x) * (d-x)).Sum();
  12.  
  13. Func<int,int> rectQuery = d =>
  14.     (from x in Enumerable.Range(0,d)
  15.     from y in Enumerable.Range(0,d)
  16.     select (d-x) * (d-y)).Sum();
  17.  
  18. (boxQuery(4) + boxQuery(2)*2).Dump();  //40 - the answer to the given image.
  19. (rectQuery(4) + rectQuery(2)*2).Dump(); //118 - the same image, but including rectangles.
  20.  
  21. //Pure mathematical representations [thanks to WolframAlpha for providing basic formula]
  22. Func<int,int> boxWolfPure = d => {d++; return ((2 * d)-1) *(d*(d-1))/6 ;};
  23. Func<int,int> rectWolfPure = d =>  {d++; return ((d-1) * (d*d*d - d*d))/4;};
  24.  
  25. //Mixed math/programming - makes use of state [all d's after and inc ++d are actually (d+1)]
  26. //Probably an abuse of code.
  27. //Func<int,int> boxWolf = d => d*++d*(2*d-1)/6;  
  28. Func<int,int> boxWolf = d => d*(d +++d)*d/6;
  29. Func<int,int> rectWolf = d => d*d*++d*d/4;
  30.  
  31. 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