Advertisement
quentez

Missing & Duplicate

Apr 24th, 2011
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. int Source[]; // The initial array.
  2.  
  3. // First, we calculate the difference between the sum of all the elements of the array and the sum of the integers from 1 to N.
  4.  
  5. int sum_ref = 0;
  6. int sum_source = 0;
  7.  
  8. int index = 0;
  9.  
  10. foreach (int i in Source)
  11. {
  12.     sum_ref += ++index;
  13.     sum_source += i;
  14. }
  15.  
  16. int diff = abs(sum_source - sum_ref);
  17.  
  18. // Now we build two sums : Sum1 (resp. Sum2) is the sum of all the integers which euclidean division by diff is even (resp. odd).
  19. // (Once again, ref is for integers 1 to N and source is for the Array)
  20.  
  21. int sum1_ref = 0;
  22. int sum1_source = 0;
  23. int sum2_ref = 0;
  24. int sum2_source = 0;
  25.  
  26. index = 0;
  27.  
  28. foreach (int i in Source)
  29. {
  30.     index++;
  31.     if (isEven(div(index, diff)))
  32.         sum1_ref += index
  33.     else
  34.         sum2_ref += index;
  35.    
  36.     if (isEven(div(i, diff)))
  37.         sum1_source += i
  38.     else
  39.         sum2_source += i;
  40. }
  41.  
  42. // Finally, the positive difference between ref and source is the missing number, and the negative one is the duplicate.
  43.  
  44. int duplicate, missing;
  45.  
  46. if (sum1_ref > sum1_source)
  47. {
  48.     missing = sum1_ref - sum1_source;
  49.     duplicate = sum2_source - sum2_ref;
  50. }
  51. else
  52. {
  53.     missing = sum2_ref - sum2_source;
  54.     duplicate = sum1_source - sum1_ref;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement