How to resolve the algorithm Semordnilap step by step in the Ruby programming language
How to resolve the algorithm Semordnilap step by step in the Ruby programming language
Table of Contents
Problem Statement
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal
This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.)
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Semordnilap step by step in the Ruby programming language
Both snippets of code are in Ruby and they solve the problem of finding words that are semordnilaps, which means that they are the same when reversed.
The first snippet reads the file "unixdict.txt" which is a list of words and removes the newline characters from each word. Then it reverses each word and sorts the list of reversed words. It then iterates over the reversed words and checks if the current word is greater than the next word in the original list of words and if the current word is less than its reverse. If both conditions are met, the word is a semordnilap and is added to the result list. Finally, the first 5 semordnilaps are printed to the console.
The second snippet also reads the file "unixdict.txt" and groups the words by their minimum value between the word and its reverse. Then it selects the groups that have a size of 2, which means that they contain a word and its reverse. Finally, the first 5 semordnilaps are printed to the console.
Source code in the ruby programming language
dict = File.readlines("unixdict.txt").collect(&:strip)
i = 0
res = dict.collect(&:reverse).sort.select do |z|
i += 1 while z > dict[i] and i < dict.length-1
z == dict[i] and z < z.reverse
end
puts "There are #{res.length} semordnilaps, of which the following are 5:"
res.take(5).each {|z| puts "#{z} #{z.reverse}"}
words = File.readlines("unixdict.txt")
.group_by{|x| [x.strip!, x.reverse].min}
.values
.select{|v| v.size==2}
puts "There are #{words.size} semordnilaps, of which the following are 5:"
words.take(5).each {|a,b| puts "#{a} #{b}"}
You may also check:How to resolve the algorithm Narcissistic decimal number step by step in the Phix programming language
You may also check:How to resolve the algorithm Ackermann function step by step in the ALGOL 60 programming language
You may also check:How to resolve the algorithm XML/XPath step by step in the AppleScript programming language
You may also check:How to resolve the algorithm Bioinformatics/base count step by step in the C programming language
You may also check:How to resolve the algorithm Magnanimous numbers step by step in the BASIC programming language