Guest User

Untitled

a guest
Feb 19th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace floatNumberAndOperators
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. var maximum = EvaluateMaximize(new double[] { 1, 12, -3 });
  14. }
  15.  
  16. /// <summary>
  17. /// Float numbers and operators: +, -, *, /
  18. /// What is the maximum number?
  19. /// code review Feb. 6, 2018
  20. /// [1, 12, -3], 33, first two numbers 1 - 12 = -11
  21. /// This function is a brute force solution.
  22. /// [1, 12, -3] brute force solution, there are 16 numbers and the maximum of 16 numbers should be 33.
  23. /// The idea to prune the algorithm is to save only 2 numbers for next round. So each round
  24. /// there are only possible 8 results, maximum and minimum values are calculated. So the total
  25. /// time complexity will be (2 * 4) * n = O(n) algorithm.
  26. /// </summary>
  27. /// <param name="terms"></param>
  28. /// <returns></returns>
  29. public static double EvaluateMaximize(double[] terms)
  30. {
  31. int N = terms.Length;
  32. if (N > 16)
  33. {
  34. throw new ArgumentException("Too complex for this solution");
  35. }
  36.  
  37. var intermediate = new double[1 << (2 * N)];
  38.  
  39. int iInterm = 0;
  40. double maximized = 0;
  41.  
  42. intermediate[iInterm++] = terms[0]; // 1
  43.  
  44. /// 1 4 4^2 in total: (4^3 - 1)/ 4 - 1
  45. /// iMaxInterm 0 4 - 1 4^2 - 1
  46. for (int index = 1; index < N; index++)
  47. {
  48. int iMaxInterm = iInterm - 1;
  49. double m = 0;
  50.  
  51. for (int iPrev = iMaxInterm; iPrev >= 0; iPrev--)
  52. {
  53. double prev = intermediate[iPrev];
  54.  
  55. var startIndex = iPrev * 4;
  56. var current = terms[index];
  57.  
  58. intermediate[startIndex + 0] = prev * current;
  59. intermediate[startIndex + 1] = prev / current;
  60. intermediate[startIndex + 2] = prev - current;
  61. intermediate[startIndex + 3] = prev + current;
  62.  
  63. if (index != N - 1) // skip if not the last term
  64. continue;
  65.  
  66. m = Math.Max(m, intermediate[startIndex + 3]);
  67. m = Math.Max(m, intermediate[startIndex + 2]);
  68. m = Math.Max(m, intermediate[startIndex + 1]);
  69. m = Math.Max(m, intermediate[startIndex + 0]);
  70. }
  71.  
  72. maximized = m;
  73. iInterm *= 4;
  74. }
  75.  
  76. return maximized;
  77. }
  78. }
  79. }
Add Comment
Please, Sign In to add comment