Created
November 21, 2013 07:45
-
-
Save suryart/7577481 to your computer and use it in GitHub Desktop.
Stackoverflow: http://stackoverflow.com/questions/20104428/palindrome-count-in-a-string Palindrome count Problem: Given a string S, count the number of non empty sub strings that are palindromes. A sub string is any continuous sequence of characters in the string. A string is said to be palindrome, if the reverse of the string is same as itself.…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
def my_method | |
string = 'dskjkd' | |
chars = string.split('') | |
counts = chars.count | |
(2..chars.count).each do |len| | |
chars.combination(len).each do |comb| | |
string = comb.inject(:<<) | |
counts += 1 if string.reverse == string | |
end | |
end | |
counts | |
end | |
def first_method | |
string = 'dskjkd' | |
b = string.chars | |
(1..b.size).reduce(0) {|t,n| t + b.each_cons(n).reduce(0) \ | |
{|r,e| w = e.join; w==w.reverse ? r + 1 : r}} | |
end | |
def second_method | |
string = 'dskjkd' | |
count = 0 | |
len = string.length | |
(0..len-1).each do |i| | |
(i..len-1).each do |j| | |
temp = string[i..j] | |
count = count + 1 if temp == temp.reverse | |
end | |
end | |
count | |
end | |
def another_method | |
string = 'dskjkd' | |
counter = 0 | |
0.upto(string.size).count do |i| | |
1.upto(string.size-i) do |j| | |
counter +=1 if string[i,j] == string[i,j].reverse | |
end | |
end | |
counter | |
end | |
def modified_another_method | |
string = 'dskjkd' | |
counter = 0 | |
0.upto(string.length).count do |i| | |
1.upto(string.length-i) do |j| | |
counter +=1 if string[i,j] == string[i,j].reverse | |
end | |
end | |
counter | |
end | |
n = 50000 | |
Benchmark.bm(40) do |x| | |
x.report("my_method "){ n.times { my_method } } | |
x.report("first_method "){ n.times { first_method } } | |
x.report("second_method "){ n.times { second_method } } | |
x.report("another_method "){ n.times { another_method } } | |
x.report("modified_another_method "){ n.times { modified_another_method } } | |
end | |
Result: | |
user system total real | |
my_method 5.110000 0.000000 5.110000 ( 5.125335) | |
first_method 1.830000 0.000000 1.830000 ( 1.831094) | |
second_method 0.700000 0.000000 0.700000 ( 0.706289) | |
another_method 0.660000 0.000000 0.660000 ( 0.664706) | |
modified_another_method 0.670000 0.000000 0.670000 ( 0.663622) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment