fork download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Test
  5. {
  6. static public void Main()
  7. {
  8. var r = new Random();
  9. for (int i = 0; i < 12; i++)
  10. {
  11. var n = r.Next(5, 10);
  12. Console.WriteLine("N={0}", n);
  13. var p = generate(n);
  14. show(p);
  15. var a = bruteforce(p);
  16. var b = median(p);
  17. Console.WriteLine("MoM={0} Med={1} Match={2}", a, b, a == b);
  18. Console.WriteLine();
  19. }
  20. }
  21.  
  22. static double median(int[] p)
  23. {
  24. Array.Sort(p);
  25. if (p.Length % 2 == 0)
  26. {
  27. var a = p[p.Length / 2];
  28. var b = p[p.Length / 2 - 1];
  29. return (a + b) / 2.0;
  30. }
  31. else
  32. {
  33. return p[p.Length / 2];
  34. }
  35. }
  36.  
  37. static double bruteforce(int[] p)
  38. {
  39. var m = new List<double>();
  40. for (int i = 0; i < p.Length; i++)
  41. {
  42. for (int j = i; j < p.Length; j++)
  43. {
  44. var t = new int[j - i + 1];
  45. Array.Copy(p, i, t, 0, t.Length);
  46. m.Add(median(t));
  47. }
  48. }
  49. m.Sort();
  50. if (m.Count % 2 == 0)
  51. {
  52. var a = m[m.Count / 2];
  53. var b = m[m.Count / 2 - 1];
  54. return (a + b) / 2.0;
  55. }
  56. else
  57. {
  58. return m[m.Count / 2];
  59. }
  60. }
  61.  
  62. static int seed = Environment.TickCount;
  63. static int[] generate(int n)
  64. {
  65. var r = new Random(seed);
  66. seed ^= r.Next();
  67. var ret = new int[n];
  68. for (int i = 0; i < n; i++)
  69. {
  70. ret[i] = r.Next(1, (int)1e3);
  71. }
  72. return ret;
  73. }
  74.  
  75. static void show(int[] arr)
  76. {
  77. foreach (int a in arr)
  78. {
  79. Console.Write("{0} ", a);
  80. }
  81. Console.WriteLine();
  82. }
  83. }
Success #stdin #stdout 0.02s 15324KB
stdin
Standard input is empty
stdout
N=8
58 714 230 199 85 800 932 130 
MoM=230 Med=214.5 Match=False

N=5
762 657 421 609 701 
MoM=633 Med=657 Match=False

N=8
930 540 83 302 772 811 727 582 
MoM=654.5 Med=654.5 Match=True

N=6
926 711 381 640 216 318 
MoM=510.5 Med=510.5 Match=True

N=5
100 402 156 684 507 
MoM=402 Med=402 Match=True

N=5
700 805 309 171 265 
MoM=309 Med=309 Match=True

N=9
220 341 73 469 207 281 142 557 152 
MoM=244 Med=220 Match=False

N=9
547 948 57 256 120 1 317 995 953 
MoM=256 Med=317 Match=False

N=5
586 650 506 967 527 
MoM=588.5 Med=586 Match=False

N=5
230 378 908 165 841 
MoM=378 Med=378 Match=True

N=9
834 583 72 525 903 944 767 175 787 
MoM=714 Med=767 Match=False

N=8
403 95 22 125 819 572 165 224 
MoM=194.5 Med=194.5 Match=True