You can try the following brute forcing method if the given array is very small
a =[1,3,4,5,2]
(1..a.length).each do |num|
a.each_cons(num).each do |pair|
return true if pair.inject(:+) == 12
end
end
return false
Otherwise try methods like this
http://www.geeksforgeeks.org/find-subarray-with-given-sum/
Regards
Aboobacker
--
You received this message because you are subscribed to the Google Groups "BANGALORE RUG-Ruby Users Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to bangalorerug...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
You can try the following brute forcing method if the given array is very small
a =[1,3,4,5,2]
(1..a.length).each do |num|
a.each_cons(num).each do |pair|
return true if pair.inject(:+) == 12
end
end
return false
The best solution here would be n.log(n) and would follow the dynamic programming.You would sort of reuse the already calculate sum and not recalculate them again.
It appears to be n^2 because of 1 nested loop.
But eventually it will be n.log(n).The nested loop goes from 0 to n-i, where i is increasing at each step.
--
--
You received this message because you are subscribed to the Google Groups "BANGALORE RUG-Ruby Users Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to bangalorerug...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
a = [1,3,4,5,2]
arr = 1.upto(5).flat_map{|n| a.combination(n).to_a}
arr.keep_if{|ar| ar.inject(0){|sum, i| sum + i} == 12 }
ar_sum = arr.keep_if{|ar| ar.inject(0){|sum, i| sum + i} == 12 }
return true unless ar_sum.blank?
Regards,
Santosh T
Please pardon me for using short variable names. I could do it in o(n)a = [1, 3, 4, 5, 2]s = 14sum_to_i = {}sum = 0a.each {|i| sum += i; sum_to_i[sum] = i}puts sum_to_i.inspectsum_to_i.keys.each {|i|if sum_to_i[i - s]print "found"exit 0end}print "not found"
--
You received this message because you are subscribed to the Google Groups "BANGALORE RUG-Ruby Users Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to bangalorerug...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Try,a = [1, 3, 4, 5, 2]s = 8it think it does not work.
--