Study the program (set of rules) below. It is supposed to write a 1 on the tape if it detects a palindrome, 0 otherwise. A palindrome is a string that reads the same forward or backward, e.g., 101, 1001, 110011. Assume your machine starts on left most digit and in state 0.
0 # # R 6 0 0 # R 2 0 1 # R 1 1 # # L 3 1 0 0 R 1 1 1 1 R 1 2 # # L 4 2 0 0 R 2 2 1 1 R 2 3 # # L 3 3 1 # L 5 4 # # L 6 4 0 # L 5 5 # # R 0 5 0 0 L 5 5 1 1 L 5 6 # 1 L h
Assume we have two sentences: one that is in the collective wisdom and one the user has typed in. I would like something similar to a google search that rates a match based on how many words the two sentences have in common. Here is the start of a method that counts words in common. The variable sent1 is what is in collective wisdom and sent2 is what user typed in.
def howManyWordsInCommon( sent1, sent2 ) #assume that both sentences are downcased and stripped of all punctuation. #your code goes here return count #number of words sent1 and sent2 have in common endLet's look at some examples.
Sent 1:what color is the sky Sent 2:the sky is what color In common: 5 Sent 1:can pigs fly Sent 2:do pigs fly In common: 2 Sent 1:what color is the ocean Sent 2:what color is the sky In common: 4I can give you a bit of help, I believe. Below is code that will enumerate all words in a sentence. Note that there is one blank/space between the two double-quotes in each method. This tells Ruby to split the sentence up using a blank as delimiter.
count = 0 s1 = "what color is the sky" s1.each(" ") do |w| w=w.strip #get rid of extraneous spaces just in case puts w count = count + 1 end puts count #should be number of words in sentence s1 (5 for s1)The variable w will get the next word in the sentence each time through the loop. Try it out in the playground.
I can also tell you that this works.
s1 = "what color is the sky" x = "sky" z = s1[x] #nil only if value of x *not* found in s1 (sky is found in s1)Try it out in playground.
Use the information above to complete the method howManyWordsInCommon(sent1,sent2). Try it with test cases above.
Side note: it would be much more useful to know how many words they do have in common *and* how many words they do not have in common, right? Perhaps as some percentage. However, you only have to count the words in common for this exercise.