Skip to content

Instantly share code, notes, and snippets.

@Nitesh-Mishra
Last active September 11, 2017 19:40
Show Gist options
  • Select an option

  • Save Nitesh-Mishra/4aed5be6b7e24614d28e95465826130d to your computer and use it in GitHub Desktop.

Select an option

Save Nitesh-Mishra/4aed5be6b7e24614d28e95465826130d to your computer and use it in GitHub Desktop.
find the 3 numbers that sum to a target number.
# Given an array of integers, find the 3 numbers that sum up to a target number.
# ruby find_3_Numbers_that_sum_to_target_number.rb
# Enter the size of array : 5
# Enter 1 element :
# 1
# Enter 2 element :
# 2
# Enter 3 element :
# 3
# Enter 4 element :
# 4
# Enter 5 element :
# 5
# Enter the target number : 12
# Triplet is : 3, 4, 5
class FindTripletNumbersThatSumToTargetNumber
def initialize
p "Enter the size of array :"
array_size = gets.strip.to_i
if array_size < 3
puts "Array size should be greater than 3"
else
array = []
for i in (0..array_size-1)
p "Enter #{i+1} element :"
array[i] = gets.strip.to_i
end
p "Enter the target number :"
target_number = gets.strip.to_i
merge_sort array
find_3_Numbers_that_sum_to_target_number(array, array_size, target_number)
end
end
def merge_sort(array)
n = array.length
if n > 1
mid = n/2
lefthalf = array[0..mid-1]
righthalf = array[mid..n-1]
merge_sort lefthalf
merge_sort righthalf
i = j = k = 0
while i < lefthalf.length and j < righthalf.length
if lefthalf[i] < righthalf[j]
array[k] = lefthalf[i]
i = i+1
else
array[k] = righthalf[j]
j = j+1
end
k += 1
end
while i < lefthalf.length
array[k] = lefthalf[i]
i = i+1
k = k+1
end
while j < righthalf.length
array[k] = righthalf[j]
j = j+1
k = k+1
end
end
end
def find_3_Numbers_that_sum_to_target_number(array, array_size, target_number)
for i in 0..array_size-2
j = i+1
k = array_size-1
for j in j..array_size-2
while j < k
if array[i] + array[j] + array[k] == target_number
puts "Triplet is : #{array[i]}, #{array[j]}, #{array[k]}"
return true
elsif
array[i] + array[j] + array[k] < target_number
j += 1
elsif array[i] + array[j] + array[k] > target_number
k += 1
end
end
end
end
puts "Triplet doesn't exist"
return false
end
end
number = FindTripletNumbersThatSumToTargetNumber.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment