Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Compare similar words in two strings

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 272
    Comment on it

    DESCRIPTION:

    Two Samurai Generals are discussing dinner plans after a battle, but they don’t appear to reach a consensus.
     
    The discussion gets heated and you cannot risk favoring either of them as this might damage your political standing with either of the two clans the samurai generals belong to. Thus, the only thing left to do is find what the common ground of what they are saying is.
     
    Compare the proposals using the function CommonGround (string a, string b). This function outputs a string containing the words that exist in both string a and string b.

    Each word in the resulting string shall occur once, and the order of the words follow the order of the first occurrence of each word in the second string.

    If they are saying nothing in common, kill both samurai and blame a ninja. (output "death")

     

    TEST CASE:

    Test.describe("Basic tests") do
    Test.assert_equals(common_ground("eat chicken", "eat chicken and rice"), 'eat chicken')
    Test.assert_equals(common_ground("eat a burger and drink a coke", "drink a coke"), 'drink a coke')
    Test.assert_equals(common_ground("i like turtles", "what are you talking about"), 'death')
    Test.assert_equals(common_ground("aa bb", "aa bb cc"), "aa bb")
    Test.assert_equals(common_ground("aa bb cc", "bb cc"), 'bb cc')
    Test.assert_equals(common_ground("aa bb cc", "bb cc bb aa"), 'bb cc aa')
    Test.assert_equals(common_ground("aa bb", "cc dd"), 'death')
    Test.assert_equals(common_ground("aa bb", ""), 'death')
    Test.assert_equals(common_ground("", "cc dd"), 'death')
    Test.assert_equals(common_ground("", ""), 'death')
    end

     

    SOLUTION

    def common_ground(s1, s2)
      words = (s1.split(' ') & s2.split(' '))
      return 'death' if words.empty?
      s2.split(' ').uniq.select{ |word| word if words.include?(word)}.join(' ')
    end

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: