Advertisement
Guest User

Untitled

a guest
Mar 28th, 2015
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. def arrayIsEqual? (numArray, x)
  2. return true if numArray.sample + numArray.sample == x
  3. return false if numArray.empty? || numArray.count == 1
  4. end
  5.  
  6. numArray = [4,2,7,5]
  7. x = 11
  8.  
  9. def contains_pair_for_sum?(arr, n)
  10. !!arr.uniq.combination(2).detect { |a, b| a + b == n }
  11. end
  12.  
  13. array = [4, 5, 9, 7, 8]
  14.  
  15. contains_pair_for_sum?(array, 11)
  16. # => true (because [4, 7] sums to 11)
  17.  
  18. contains_pair_for_sum?(array, 17)
  19. # => true (because [9, 8] sums to 17)
  20.  
  21. contains_pair_for_sum?(array, 100)
  22. # => false (no pair matched)
  23.  
  24. def has_pair_equal?(num_array, x)
  25. (0..num_array.length-1).any? do |i|
  26. num_array[i+1..-1].any? { |n| n + num_array[i] == x }
  27. end
  28. end
  29.  
  30. def array_is_equal? (num_array, x)
  31. equality = 0
  32. num_array.each do |a|
  33. equality += 1 if a == x
  34. return true if equality == 2
  35. end
  36. return false
  37. end
  38.  
  39. x=[4,2,7,5]; x.each_with_index.any? {|y,i| x.each_with_index.any? {|z,j| unless i==j; z+y==11; end } }
  40.  
  41. def pair_sum_match?(arr, x)
  42. arr.each_with_index.any? do |y,i|
  43. arr.each_with_index.any? do |z,j|
  44. unless i==j
  45. z+y==x
  46. end
  47. end
  48. end
  49. end
  50.  
  51. numbers = ( -10..10 ).to_a
  52. numbers.unshift( numbers.first + -1 ) # if you do -20 or 20
  53. numbers.push( numbers.last + 1 )
  54. target = 5
  55. searched = { }
  56. matches = { }
  57. numbers.each do |number|
  58. if searched[ target - number + 1 ] == true
  59. matches[ "#{ number }_plus_#{ target - number }" ] = target
  60. end
  61. searched[ number + 1 ] = true
  62. end
  63. ap matches
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement