Reputation: 118
class Triplet
def initialize(array,sum)
@array = array.sort()
@array_size = array.size()
@sum = sum
@result = []
end
def get_triplet
@array[0..-3].each_with_index do |arr, ind|
pointer_one = ind + 1
pointer_two = @array_size - 1
while (pointer_one < pointer_two)
temp_sum = @array[pointer_one] + @array[pointer_two] + arr
if(temp_sum == @sum)
@result.push([@array[pointer_one], @array[pointer_two], arr])
elsif temp_sum < @sum
pointer_one = pointer_one +1
else
pointer_two = pointer_two -1
end
end
end
end
def get_result
@result.each do |res|
puts res
end
end
end
puts "Enter the array of numbers"
array = gets.chomp
array = array.split(' ')
array_integer = array.map{|a| a.to_i}
puts array_integer
puts "Enter the sum"
sum = gets.chomp
puts sum
t1 = Triplet.new(array_integer,sum.to_i)
t1.get_triplet
t1.get_result
Can anyone suggest me the fix so that it doesn't loop infinitly. It is program to find triplet in array whose sum is @sum. Its looping in get_triplet method. Initialize method sets the array,array size. get_triplet method should store all three number whose sum is @sum in result array.
Upvotes: 0
Views: 48
Reputation: 211580
Usually a tangle of code like this is a sign something's not right, and in this case the source of the problem is not knowing about the combination
method. Here's a functionally equivalent solution:
def triplet(list, target)
list.combination(3).find do |a,b,c|
a + b + c == target
end
end
For example:
arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
p triplet(arr, 6)
# => [1, 2, 3]
p triplet(arr, 4)
# => nil
p triplet(arr, 10)
# => [1, 2, 7]
The algorithm used in your code looks problematic, or at least implemented incorrectly, and is also strictly limited to triplets. This code is far more generic and uses a proven, tested algorithm, so it's probably better suited to solving your particular problem.
Upvotes: 2