Advertisement
sidhartha11

Untitled

Mar 1st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. package org.geo.scala.fundamentals.examples.tricks
  2.  
  3. object missingNumber extends App {
  4. def findMissing(arr: Array[Int]): Int = {
  5. /** get length of array **/
  6. val len = arr.length + 1
  7. /** determine sum of array **/
  8. val sum = arr.sum
  9. /** determine sum of complete array **/
  10. val sumComplete = (len * ( len + 1 ))/2
  11. /** determine missing number **/
  12. sumComplete - sum
  13. }
  14.  
  15. def findMissingXor(arr: Array[Int]): Int = {
  16. /** get the length of the array + 1 **/
  17. val len = arr.length + 1
  18. /** perform a fold left operation **/
  19. var n = (0 /: arr)(_ ^ _)
  20. /** now exclusiveor with the complete array **/
  21. val x = (1 to len).foldLeft(n)(_ ^ _)
  22. x
  23. }
  24.  
  25. /** test it **/
  26. /** fill an array with 99 entries missing the 8th entry **/
  27. var arr = new Array[Int](100).indices.map(p => p + 1).filter(_ != 8).toArray[Int]
  28. /** find the missing value 8 **/
  29. println("missing number is " + findMissing(arr))
  30.  
  31. /** find the missing value 45 **/
  32. arr = new Array[Int](100).indices.map(p => p + 1).filter(_ != 45).toArray[Int]
  33. println("missing number is " + findMissing(arr))
  34.  
  35. /** try the xor version **/
  36. println("missing number is " + findMissingXor(arr))
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement