title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Substring/Top and tail
Ruby
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: * String with first character removed * String with last character removed * String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
puts "knight"[1..-1] # strip first character puts "socks"[0..-2] # strip last character puts "socks".chop # alternate way to strip last character puts "brooms"[1..-2] # strip both first and last characters puts "与今令"[1..-2] # => 今
Sum and product puzzle
Ruby from D
* Wikipedia: Sum and Product Puzzle
def add(x,y) x + y end def mul(x,y) x * y end def sumEq(s,p) s.select{|q| add(*p) == add(*q)} end def mulEq(s,p) s.select{|q| mul(*p) == mul(*q)} end s1 = (a = *2...100).product(a).select{|x,y| x<y && x+y<100} s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size != 1} } s3 = s2.select{|p| (mulEq(s1,p) & s2).size == 1} p s3.select{|p| (sumEq(s1,p) & s3).size == 1}
Sum multiples of 3 and 5
Ruby
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. Show output for ''n'' = 1000. This is is the same as Project Euler problem 1. '''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
# Given two integers n1,n2 return sum of multiples upto n3 # # Nigel_Galloway # August 24th., 2013. def g(n1, n2, n3) g1 = n1*n2 (1..g1).select{|x| x%n1==0 or x%n2==0}.collect{|x| g2=(n3-x)/g1; (x+g1*g2+x)*(g2+1)}.inject{|sum,x| sum+x}/2 end puts g(3,5,999) # For extra credit puts g(3,5,100000000000000000000-1)
Sum multiples of 3 and 5
Ruby from D
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. Show output for ''n'' = 1000. This is is the same as Project Euler problem 1. '''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
def sumMul(n, f) n1 = (n - 1) / f f * n1 * (n1 + 1) / 2 end def sum35(n) sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15) end for i in 1..20 puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)] end
Sum of elements below main diagonal of matrix
Ruby
Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ::: --- Matrix to be used: --- [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
arr = [ [ 1, 3, 7, 8, 10], [ 2, 4, 16, 14, 4], [ 3, 1, 9, 18, 11], [12, 14, 17, 18, 20], [ 7, 1, 3, 9, 5] ] p arr.each_with_index.sum {|row, x| row[0, x].sum}
Sum to 100
Ruby
Find solutions to the ''sum to one hundred'' puzzle. Add (insert) the mathematical operators '''+''' or '''-''' (plus or minus) before any of the digits in the decimal numeric string '''123456789''' such that the resulting mathematical expression adds up to a particular sum (in this iconic case, '''100'''). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here. :* Show all solutions that sum to '''100''' :* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++) :* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task :* Show the ten highest numbers that can be expressed using the rules for this task (extra credit) ++ (where ''infinity'' would be a relatively small 123,456,789) An example of a sum that can't be expressed (within the rules of this task) is: '''5074''' (which, of course, isn't the lowest positive sum that can't be expressed).
digits = ("1".."9").to_a ar = ["+", "-", ""].repeated_permutation(digits.size).filter_map do |op_perm| str = op_perm.zip(digits).join str unless str.start_with?("+") end res = ar.group_by{|str| eval(str)} puts res[100] , "" sum, solutions = res.max_by{|k,v| v.size} puts "#{sum} has #{solutions.size} solutions.", "" no_solution = (1..).find{|n| res[n] == nil} puts "#{no_solution} is the lowest positive number without a solution.", "" puts res.max(10).map{|pair| pair.join(": ")}
Summarize and say sequence
Ruby
There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) ;Task: Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 ;Related tasks: * [[Fours is the number of letters in the ...]] * [[Look-and-say sequence]] * [[Number names]] * [[Self-describing numbers]] * [[Spelling of ordinal numbers]] ;Also see: * The On-Line Encyclopedia of Integer Sequences.
$cache = {} def selfReferentialSequence_cached(n, seen = []) return $cache[n] if $cache.include? n return [] if seen.include? n digit_count = Array.new(10, 0) n.to_s.chars.collect {|char| digit_count[char.to_i] += 1} term = '' 9.downto(0).each do |d| if digit_count[d] > 0 term += digit_count[d].to_s + d.to_s end end term = term.to_i $cache[n] = [n] + selfReferentialSequence_cached(term, [n] + seen) end limit = 1_000_000 max_len = 0 max_vals = [] 1.upto(limit - 1) do |n| seq = selfReferentialSequence_cached(n) if seq.length > max_len max_len = seq.length max_vals = [n] elsif seq.length == max_len max_vals << n end end puts "values: #{max_vals.inspect}" puts "iterations: #{max_len}" puts "sequence:" selfReferentialSequence_cached(max_vals[0]).each_with_index do |val, idx| puts "%2d %d" % [idx + 1, val] end
Summarize primes
Ruby from C++
Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
def isPrime(n) if n < 2 then return false end if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end i = 5 while i * i <= n if n % i == 0 then return false end i += 2 if n % i == 0 then return false end i += 4 end return true end START = 1 STOP = 1000 sum = 0 count = 0 sc = 0 for p in START .. STOP if isPrime(p) then count += 1 sum += p if isPrime(sum) then print "The sum of %3d primes in [2, %3d] is %5d which is also prime\n" % [count, p, sum] sc += 1 end end end print "There are %d summerized primes in [%d, %d]\n" % [sc, START, STOP]
Super-d numbers
Ruby
A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where 2 <= d <= 9 For instance, 753 is a super-3 number because 3 x 7533 = 1280873331. '''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''. ;Task: :* Write a function/procedure/routine to find super-d numbers. :* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers. ;Extra credit: :* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional). ;See also: :* Wolfram MathWorld - Super-d Number. :* OEIS: A014569 - Super-3 Numbers.
(2..8).each do |d| rep = d.to_s * d print "#{d}: " puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ") end
Superpermutation minimisation
Ruby
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches. ;Reference: * The Minimal Superpermutation Problem. by Nathaniel Johnston. * oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. * Superpermutations - Numberphile. A video * Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. * New Superpermutations Discovered! Standupmaths & Numberphile.
#A straight forward implementation of N. Johnston's algorithm. I prefer to look at this as 2n+1 where #the second n is first n reversed, and the 1 is always the second symbol. This algorithm will generate #just the left half of the result by setting l to [1,2] and looping from 3 to 6. For the purpose of #this task I am going to start from an empty array and generate the whole strings using just the #rules. # #Nigel Galloway: December 16th., 2014 # l = [] (1..6).each{|e| a, i = [], e-2 (0..l.length-e+1).each{|g| if not (n = l[g..g+e-2]).uniq! a.concat(n[(a[0]? i : 0)..-1]).push(e).concat(n) i = e-2 else i -= 1 end } a.each{|n| print n}; puts "\n\n" l = a }
Sylvester's sequence
Ruby
{{Wikipedia|Sylvester's sequence}} In number theory, '''Sylvester's sequence''' is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to '''1''' more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first '''k''' terms of the infinite series of reciprocals provides the closest possible underestimate of '''1''' by any k-term Egyptian fraction. ;Task: * Write a routine (function, procedure, generator, whatever) to calculate '''Sylvester's sequence'''. * Use that routine to show the values of the first '''10''' elements in the sequence. * Show the sum of the reciprocals of the first '''10''' elements on the sequence, ideally as an exact fraction. ;Related tasks: * [[Egyptian fractions]] * [[Harmonic series]] ;See also: * OEIS A000058 - Sylvester's sequence
def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 } (0..9).each {|n| puts "#{n}: #{sylvester n}" } puts " Sum of reciprocals of first 10 terms: #{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }"
Tau function
Ruby
Given a positive integer, count the number of its positive divisors. ;Task Show the result for the first '''100''' positive integers. ;Related task * [[Tau number]]
require 'prime' def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1} (1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
Teacup rim text
Ruby
On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*). It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word. So start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''. That got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu. For English, we will use the unixdict (now) located at: unixdict.txt. (This will maintain continuity with other Rosetta Code tasks that also use it.) ;Task: Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.) Having listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc. The words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.) The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''. All of the possible permutations, using this particular permutation technique, must be words in the list. The set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method. Display one line for each set of teacup rim words.
lists = ["unixdict.txt", "wordlist.10000", "woordenlijst.txt"] lists.each do |list| words = open(list).readlines( chomp: true).reject{|w| w.size < 3 } grouped_by_size = words.group_by(&:size) tea_words = words.filter_map do |word| chars = word.chars next unless chars.none?{|c| c < chars.first } next if chars.uniq.size == 1 rotations = word.size.times.map {|i| chars.rotate(i).join } rotations if rotations.all?{|rot| grouped_by_size[rot.size].include? rot } end puts "", list + ":" tea_words.uniq(&:to_set).each{|ar| puts ar.join(", ") } end
Temperature conversion
Ruby
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. : 0 degrees Celsius corresponds to 273.15 kelvin. : 0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. : 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. : 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. ;Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. ;Example: K 21.00 C -252.15 F -421.87 R 37.80
module TempConvert FROM_TEMP_SCALE_TO_K = {'kelvin' => lambda{|t| t}, 'celsius' => lambda{|t| t + 273.15}, 'fahrenheit' => lambda{|t| (t + 459.67) * 5/9.0}, 'rankine' => lambda{|t| t * 5/9.0}, 'delisle' => lambda{|t| 373.15 - t * 2/3.0}, 'newton' => lambda{|t| t * 100/33.0 + 273.15}, 'reaumur' => lambda{|t| t * 5/4.0 + 273.15}, 'roemer' => lambda{|t| (t - 7.5) * 40/21.0 + 273.15}} TO_TEMP_SCALE_FROM_K = {'kelvin' => lambda{|t| t}, 'celsius' => lambda{|t| t - 273.15}, 'fahrenheit' => lambda{|t| t * 9/5.0 - 459.67}, 'rankine' => lambda{|t| t * 9/5.0}, 'delisle' => lambda{|t| (373.15 - t) * 3/2.0}, 'newton' => lambda{|t| (t - 273.15) * 33/100.0}, 'reaumur' => lambda{|t| (t - 273.15) * 4/5.0}, 'roemer' => lambda{|t| (t - 273.15) * 21/40.0 + 7.5}} SUPPORTED_SCALES = FROM_TEMP_SCALE_TO_K.keys.join('|') def self.method_missing(meth, *args, &block) if valid_temperature_conversion?(meth) then convert_temperature(meth, *args) else super end end def self.respond_to_missing?(meth, include_private = false) valid_temperature_conversion?(meth) || super end def self.valid_temperature_conversion?(meth) !!(meth.to_s =~ /(#{SUPPORTED_SCALES})_to_(#{SUPPORTED_SCALES})/) end def self.convert_temperature(meth, temp) from_scale, to_scale = meth.to_s.split("_to_") return temp.to_f if from_scale == to_scale # no kelvin roundtrip TO_TEMP_SCALE_FROM_K[to_scale].call(FROM_TEMP_SCALE_TO_K[from_scale].call(temp)).round(2) end end
Terminal control/Unicode output
Ruby
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
#encoding: UTF-8 # superfluous in Ruby >1.9.3 if ENV.values_at("LC_ALL","LC_CTYPE","LANG").compact.first.include?("UTF-8") puts "△" else raise "Terminal can't handle UTF-8" end
Test integerness
Ruby
{| class="wikitable" |- ! colspan=2 | Input ! colspan=2 | Output ! rowspan=2 | Comment |- ! Type ! Value ! exact ! tolerance = 0.00001 |- | rowspan=3 | decimal | 25.000000 | colspan=2 | true | |- | 24.999999 | false | true | |- | 25.000100 | colspan=2 | false | |- | rowspan=4 | floating-point | -2.1e120 | colspan=2 | true | This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such. |- | -5e-2 | colspan=2 | false | |- | NaN | colspan=2 | false | |- | Inf | colspan=2 | false | This one is debatable. If your code considers it an integer, that's okay too. |- | rowspan=2 | complex | 5.0+0.0i | colspan=2 | true | |- | 5-5i | colspan=2 | false | |} (The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
class Numeric def to_i? self == self.to_i rescue false end end # Demo ar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, # Floats Float::NAN, Float::INFINITY, # more Floats 2r, 2.5r, # Rationals 2+0i, 2+0.0i, 5-5i] # Complexes ar.each{|num| puts "#{num} integer? #{num.to_i?}" }
Textonyms
Ruby
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -> WXYZ ;Task: Write a program that finds textonyms in a list of words such as [[Textonyms/wordlist]] or unixdict.txt. The task should produce a report: There are #{0} words in #{1} which can be represented by the digit key mapping. They require #{2} digit combinations to represent them. #{3} digit combinations represent Textonyms. Where: #{0} is the number of words in the list which can be represented by the digit key mapping. #{1} is the URL of the wordlist being used. #{2} is the number of digit combinations required to represent the words in #{0}. #{3} is the number of #{2} which represent more than one word. At your discretion show a couple of examples of your solution displaying Textonyms. E.G.: 2748424767 -> "Briticisms", "criticisms" ;Extra credit: Use a word list and keypad mapping other than English.
CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" NUMS = "22233344455566677778889999" * 2 dict = "unixdict.txt" textonyms = File.open(dict){|f| f.map(&:chomp).group_by {|word| word.tr(CHARS, NUMS) } } puts "There are #{File.readlines(dict).size} words in #{dict} which can be represented by the digit key mapping. They require #{textonyms.size} digit combinations to represent them. #{textonyms.count{|_,v| v.size > 1}} digit combinations represent Textonyms." puts "\n25287876746242: #{textonyms["25287876746242"].join(", ")}"
The Name Game
Ruby 2.7.1
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like this: Gary, Gary, bo-bary Banana-fana fo-fary Fee-fi-mo-mary Gary! At the end of every line, the name gets repeated without the first letter: Gary becomes ary If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this: (X), (X), bo-b(Y) Banana-fana fo-f(Y) Fee-fi-mo-m(Y) (X)! Vowel as first letter of the name If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name. The verse looks like this: Earl, Earl, bo-bearl Banana-fana fo-fearl Fee-fi-mo-mearl Earl! 'B', 'F' or 'M' as first letter of the name In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule. The line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name. The verse for the name Billy looks like this: Billy, Billy, bo-illy Banana-fana fo-filly Fee-fi-mo-milly Billy! For the name 'Felix', this would be right: Felix, Felix, bo-belix Banana-fana fo-elix Fee-fi-mo-melix Felix!
#!/usr/bin/env ruby def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize # X suffixed = case full_name[0] # Y when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b#{suffixed}" f_name = "f#{suffixed}" m_name = "m#{suffixed}" case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE #{full_name}, #{full_name}, bo-#{b_name} Banana-fana fo-#{f_name} Fee-fi-mo-#{m_name} #{full_name}! END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
The Twelve Days of Christmas
Ruby
Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
gifts = "A partridge in a pear tree Two turtle doves and Three french hens Four calling birds Five golden rings Six geese a-laying Seven swans a-swimming Eight maids a-milking Nine ladies dancing Ten lords a-leaping Eleven pipers piping Twelve drummers drumming".split("\n") days = %w(first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth) days.each_with_index do |day, i| puts "On the #{day} day of Christmas" puts "My true love gave to me:" puts gifts[0, i+1].reverse puts end
Top rank per group
Ruby 2.2+
Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
require "csv" data = <<EOS Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190 EOS def show_top_salaries_per_group(data, n) table = CSV.parse(data, :headers=>true, :header_converters=>:symbol) groups = table.group_by{|emp| emp[:department]}.sort groups.each do |dept, emps| puts dept # max by salary emps.max_by(n) {|emp| emp[:salary].to_i}.each do |e| puts " %-16s %6s %7d" % [e[:employee_name], e[:employee_id], e[:salary]] end puts end end show_top_salaries_per_group(data, 3)
Topic variable
Ruby
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language. For instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 to it and then computing its square and square root.
while DATA.gets # assigns to $_ (local scope) print # If no arguments are given, prints $_ end __END__ This is line one This is line two This is line three
Topswops
Ruby from Python
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. A round is composed of reversing the first m cards where m is the value of the topmost card. Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top. For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards. ;Task: The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive. ;Note: Topswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake. ;Related tasks: * [[Number reversal game]] * [[Sorting algorithms/Pancake sort]]
def f1(a) i = 0 while (a0 = a[0]) > 1 a[0...a0] = a[0...a0].reverse i += 1 end i end def fannkuch(n) [*1..n].permutation.map{|a| f1(a)}.max end for n in 1..10 puts "%2d : %d" % [n, fannkuch(n)] end
Topswops
Ruby from Java
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. A round is composed of reversing the first m cards where m is the value of the topmost card. Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top. For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards. ;Task: The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive. ;Note: Topswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake. ;Related tasks: * [[Number reversal game]] * [[Sorting algorithms/Pancake sort]]
def try_swaps(deck, f, d, n) @best[n] = d if d > @best[n] (n-1).downto(0) do |i| break if deck[i] == -1 || deck[i] == i return if d + @best[i] <= @best[n] end deck2 = deck.dup for i in 1...n k = 1 << i if deck2[i] == -1 next if f & k != 0 elsif deck2[i] != i next end deck2[0] = i deck2[1..i] = deck[0...i].reverse try_swaps(deck2, f | k, d+1, n) end end def topswops(n) @best[n] = 0 deck0 = [-1] * (n + 1) try_swaps(deck0, 1, 0, n) @best[n] end @best = [0] * 16 for i in 1..10 puts "%2d : %d" % [i, topswops(i)] end
Total circles area
Ruby
Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks): xc yc radius 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 The result is 21.56503660... . ;Related task: * [[Circles of given radius through two points]]. ;See also: * http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ * http://stackoverflow.com/a/1667789/10562
circles = [ [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832854473, 1.0845181219], [ 1.7813504266, 1.6178237031, 0.8162655711], [-0.1985249206, -0.8343333301, 0.0538864941], [-1.7011985145, -0.1263820964, 0.4776976918], [-0.4319462812, 1.4104420482, 0.7886291537], [ 0.2178372997, -0.9499557344, 0.0357871187], [-0.6294854565, -1.3078893852, 0.7653357688], [ 1.7952608455, 0.6281269104, 0.2727652452], [ 1.4168575317, 1.0683357171, 1.1016025378], [ 1.4637371396, 0.9463877418, 1.1846214562], [-0.5263668798, 1.7315156631, 1.4428514068], [-1.2197352481, 0.9144146579, 1.0727263474], [-0.1389358881, 0.1092805780, 0.7350208828], [ 1.5293954595, 0.0030278255, 1.2472867347], [-0.5258728625, 1.3782633069, 1.3495508831], [-0.1403562064, 0.2437382535, 1.3804956588], [ 0.8055826339, -0.0482092025, 0.3327165165], [-0.6311979224, 0.7184578971, 0.2491045282], [ 1.4685857879, -0.8347049536, 1.3670667538], [-0.6855727502, 1.6465021616, 1.0593087096], [ 0.0152957411, 0.0638919221, 0.9771215985], ] def minmax_circle(circles) xmin = circles.map {|xc, yc, radius| xc - radius}.min xmax = circles.map {|xc, yc, radius| xc + radius}.max ymin = circles.map {|xc, yc, radius| yc - radius}.min ymax = circles.map {|xc, yc, radius| yc + radius}.max [xmin, xmax, ymin, ymax] end # remove internal circle def select_circle(circles) circles = circles.sort_by{|cx,cy,r| -r} size = circles.size select = [*0...size] for i in 0...size-1 xi,yi,ri = circles[i].to_a for j in i+1...size xj,yj,rj = circles[j].to_a select -= [j] if (xi-xj)**2 + (yi-yj)**2 <= (ri-rj)**2 end end circles.values_at(*select) end circles = select_circle(circles)
Total circles area
Ruby from Python
Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks): xc yc radius 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.0538864941 -1.7011985145 -0.1263820964 0.4776976918 -0.4319462812 1.4104420482 0.7886291537 0.2178372997 -0.9499557344 0.0357871187 -0.6294854565 -1.3078893852 0.7653357688 1.7952608455 0.6281269104 0.2727652452 1.4168575317 1.0683357171 1.1016025378 1.4637371396 0.9463877418 1.1846214562 -0.5263668798 1.7315156631 1.4428514068 -1.2197352481 0.9144146579 1.0727263474 -0.1389358881 0.1092805780 0.7350208828 1.5293954595 0.0030278255 1.2472867347 -0.5258728625 1.3782633069 1.3495508831 -0.1403562064 0.2437382535 1.3804956588 0.8055826339 -0.0482092025 0.3327165165 -0.6311979224 0.7184578971 0.2491045282 1.4685857879 -0.8347049536 1.3670667538 -0.6855727502 1.6465021616 1.0593087096 0.0152957411 0.0638919221 0.9771215985 The result is 21.56503660... . ;Related task: * [[Circles of given radius through two points]]. ;See also: * http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ * http://stackoverflow.com/a/1667789/10562
def area_scan(prec, circles) sect = ->(y) do circles.select{|cx,cy,r| (y - cy).abs < r}.map do |cx,cy,r| dr = Math.sqrt(r ** 2 - (y - cy) ** 2) [cx - dr, cx + dr] end end xmin, xmax, ymin, ymax = minmax_circle(circles) ymin = (ymin / prec).floor ymax = (ymax / prec).ceil total = 0 for y in ymin..ymax y *= prec right = xmin for x0, x1 in sect[y].sort next if x1 <= right total += x1 - [x0, right].max right = x1 end end total * prec end puts "Scanline Method" prec = 1e-2 3.times do t0 = Time.now puts "%8.6f : %12.9f, %p sec" % [prec, area_scan(prec, circles), Time.now-t0] prec /= 10 end
Trabb Pardo–Knuth algorithm
Ruby
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: '''ask''' for 11 numbers to be read into a sequence ''S'' '''reverse''' sequence ''S'' '''for each''' ''item'' '''in''' sequence ''S'' ''result'' ''':=''' '''call''' a function to do an ''operation'' '''if''' ''result'' overflows '''alert''' user '''else''' '''print''' ''result'' The task is to implement the algorithm: # Use the function: f(x) = |x|^{0.5} + 5x^3 # The overflow condition is an answer of greater than 400. # The 'user alert' should not stop processing of other items of the sequence. # Print a prompt before accepting '''eleven''', textual, numeric inputs. # You may optionally print the item as well as its associated result, but the results must be in reverse order of input. # The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly. # ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
def f(x) x.abs ** 0.5 + 5 * x ** 3 end puts "Please enter 11 numbers:" nums = 11.times.map{ gets.to_f } nums.reverse_each do |n| print "f(#{n}) = " res = f(n) puts res > 400 ? "Overflow!" : res end
Truncate a file
Ruby
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
# Open a file for writing, and truncate it to 1234 bytes. File.open("file", "ab") do |f| f.truncate(1234) f << "Killroy was here" # write to file end # file is closed now. # Just truncate a file to 567 bytes. File.truncate("file", 567)
Truth table
Ruby
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. ;Task: # Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). # Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. # Either reverse-polish or infix notation expressions are allowed. ;Related tasks: * [[Boolean values]] * [[Ternary logic]] ;See also: * Wolfram MathWorld entry on truth tables. * some "truth table" examples from Google.
loop do print "\ninput a boolean expression (e.g. 'a & b'): " expr = gets.strip.downcase break if expr.empty? vars = expr.scan(/\p{Alpha}+/) if vars.empty? puts "no variables detected in your boolean expression" next end vars.each {|v| print "#{v}\t"} puts "| #{expr}" prefix = [] suffix = [] vars.each do |v| prefix << "[false, true].each do |#{v}|" suffix << "end" end body = vars.inject("puts ") {|str, v| str + "#{v}.to_s + '\t' + "} body += '"| " + eval(expr).to_s' eval (prefix + [body] + suffix).join("\n") end
Two bullet roulette
Ruby
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. ;Task: # Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. # Show the results as a percentage of deaths for each type of scenario. # The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. ;Reference: Youtube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]
class Revolver attr_accessor :strategy attr_reader :notches, :shot_count def initialize(strategy = [:load, :spin, :shoot], num_chambers = 6) # default like Deer hunter @chambers = Array.new(num_chambers) # by default 6 nils @strategy = strategy @notches, @shot_count, @loaded_count = 0, 0, 0 end def load raise "gun completely loaded " if @chambers.all? :loaded @chambers.rotate! until @chambers[1] == nil #not sure about this; Raku rotates -1 @chambers[1] = :loaded @chambers.rotate! #not sure about this; Raku rotates -1 @loaded_count += 1 end def spin @chambers.rotate!(rand(1..@chambers.size)) end def unload @chambers.fill(nil) @loaded_count = 0 end def shoot @chambers[0] = nil @chambers.rotate! end def play strategy.each{|action| send(action)} @shot_count += 1 @notches += 1 unless @chambers.count(:loaded) == @loaded_count # all bullets still there? unload end end strategies = {:A => [:load, :spin, :load, :spin, :shoot, :spin, :shoot], :B => [:load, :spin, :load, :spin, :shoot, :shoot], :C => [:load, :load, :spin, :shoot, :spin, :shoot], :D => [:load, :load, :spin, :shoot, :shoot], :E => [:load, :spin, :shoot, :load, :spin, :shoot]} n = 100_000 puts "simulation of #{n} runs:" strategies.each do |name, strategy| gun = Revolver.new(strategy) # Revolver.new(strategy, 10) for a 10-shooter n.times{gun.play} puts "Strategy #{name}: #{gun.notches.fdiv(gun.shot_count)}" end
UPC
Ruby from C
Goal: Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink). ;Sample input: Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down, and one entry has a timing error. ;Task: Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down (the other option is to reject them). ;Notes: Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''. On the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1''' Alternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code. ;The UPC-A bar code structure: ::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly), ::* then has a ''' # # ''' sequence marking the start of the sequence, ::* then has the six "left hand" digits, ::* then has a ''' # # ''' sequence in the middle, ::* then has the six "right hand digits", ::* then has another ''' # # ''' (end sequence), and finally, ::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. ;Verification: Multiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products. The sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.
DIGIT_F = { " ## #" => 0, " ## #" => 1, " # ##" => 2, " #### #" => 3, " # ##" => 4, " ## #" => 5, " # ####" => 6, " ### ##" => 7, " ## ###" => 8, " # ##" => 9, } DIGIT_R = { "### # " => 0, "## ## " => 1, "## ## " => 2, "# # " => 3, "# ### " => 4, "# ### " => 5, "# # " => 6, "# # " => 7, "# # " => 8, "### # " => 9, } END_SENTINEL = "# #" MID_SENTINEL = " # # " def decode_upc(s) def decode_upc_impl(input) upc = input.strip if upc.length != 95 then return false end pos = 0 digits = [] sum = 0 # end sentinel if upc[pos .. pos + 2] == END_SENTINEL then pos += 3 else return false end # 6 left hand digits for i in 0 .. 5 digit = DIGIT_F[upc[pos .. pos + 6]] if digit == nil then return false else digits.push(digit) sum += digit * [1, 3][digits.length % 2] pos += 7 end end # mid sentinel if upc[pos .. pos + 4] == MID_SENTINEL then pos += 5 else return false end # 6 right hand digits for i in 0 .. 5 digit = DIGIT_R[upc[pos .. pos + 6]] if digit == nil then return false else digits.push(digit) sum += digit * [1, 3][digits.length % 2] pos += 7 end end # end sentinel if upc[pos .. pos + 2] == END_SENTINEL then pos += 3 else return false end if sum % 10 == 0 then print digits, " " return true else print "Failed Checksum " return false end end if decode_upc_impl(s) then puts "Rightside Up" elsif decode_upc_impl(s.reverse) then puts "Upside Down" else puts "Invalid digit(s)" end end def main num = 0 print "%2d: " % [num += 1] decode_upc(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ") print "%2d: " % [num += 1] decode_upc(" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ") print "%2d: " % [num += 1] decode_upc(" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ") print "%2d: " % [num += 1] decode_upc(" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ") print "%2d: " % [num += 1] decode_upc(" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ") print "%2d: " % [num += 1] decode_upc(" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ") print "%2d: " % [num += 1] decode_upc(" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ") print "%2d: " % [num += 1] decode_upc(" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ") print "%2d: " % [num += 1] decode_upc(" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ") print "%2d: " % [num += 1] decode_upc(" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ") end main()
URL decoding
Ruby
This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. ;Test cases: * The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/". * The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Baha". * The encoded string "%25%32%35" should revert to the unencoded form "%25" and '''not''' "%".
require 'cgi' puts CGI.unescape("http%3A%2F%2Ffoo%20bar%2F") # => "http://foo bar/"
URL decoding
Ruby 1.9.2
This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. ;Test cases: * The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/". * The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Baha". * The encoded string "%25%32%35" should revert to the unencoded form "%25" and '''not''' "%".
require 'uri' puts URI.decode_www_form_component("http%3A%2F%2Ffoo%20bar%2F") # => "http://foo bar/"
URL encoding
Ruby
Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: * ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). * ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) * ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) * ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) * ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) * Extended characters with character codes of 128 decimal (80 hex) and above. ;Example: The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". ;Variations: * Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". * Special characters have different encodings for different standards: ** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~". ** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". ** encodeURI function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#". ;Options: It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. ;Related tasks: * [[URL decoding]] * [[URL parser]]
require 'cgi' puts CGI.escape("http://foo bar/").gsub("+", "%20") # => "http%3A%2F%2Ffoo%20bar%2F"
URL encoding
Ruby 1.9.2
Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: * ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). * ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) * ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) * ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) * ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) * Extended characters with character codes of 128 decimal (80 hex) and above. ;Example: The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". ;Variations: * Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". * Special characters have different encodings for different standards: ** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~". ** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". ** encodeURI function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#". ;Options: It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. ;Related tasks: * [[URL decoding]] * [[URL parser]]
require 'uri' puts URI.encode_www_form_component("http://foo bar/").gsub("+", "%20") # => "http%3A%2F%2Ffoo%20bar%2F"
URL parser
Ruby
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id ;Task: Parse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ... Note: this task has nothing to do with [[URL encoding]] or [[URL decoding]]. According to the standards, the characters: :::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded ('''%''') in case of possible confusion. Also note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics. * Here is the official standard: https://tools.ietf.org/html/rfc3986, * and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html. ;Test cases: According to T. Berners-Lee '''foo://example.com:8042/over/there?name=ferret#nose''' should parse into: ::* scheme = foo ::* domain = example.com ::* port = :8042 ::* path = over/there ::* query = name=ferret ::* fragment = nose '''urn:example:animal:ferret:nose''' should parse into: ::* scheme = urn ::* path = example:animal:ferret:nose '''other URLs that must be parsed include:''' :* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true :* ftp://ftp.is.co.za/rfc/rfc1808.txt :* http://www.ietf.org/rfc/rfc2396.txt#header1 :* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two :* mailto:John.Doe@example.com :* news:comp.infosystems.www.servers.unix :* tel:+1-816-555-1212 :* telnet://192.0.2.16:80/ :* urn:oasis:names:specification:docbook:dtd:xml:4.1.2
require 'uri' test_cases = [ "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] class URI::Generic; alias_method :domain, :host; end test_cases.each do |test_case| puts test_case uri = URI.parse(test_case) %w[ scheme domain port path query fragment user password ].each do |attr| puts " #{attr.rjust(8)} = #{uri.send(attr)}" if uri.send(attr) end end
UTF-8 encode and decode
Ruby
As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 o LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Zh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 EUR EURO SIGN U+20AC E2 82 AC MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
character_arr = ["A","ö","Ж","€","𝄞"] for c in character_arr do puts "Character: " + c.encode("utf-8") puts "Code-Point: #{c.encode("utf-8").ord.to_s(16).upcase}" puts "Code-Units: " + c.each_byte.map { |n| '%02X ' % (n & 0xFF) }.join puts "" end
Ultra useful primes
Ruby
An '''ultra-useful prime''' is a member of the sequence where each '''a(n)''' is the smallest positive integer '''k''' such that '''2(2n) - k''' is prime. '''''k''' must always be an odd number since 2 to any power is always even.'' ;Task * Find and show here, on this page, the first '''10''' elements of the sequence. ;Stretch * Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.) ;See also * OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
require 'openssl' (1..10).each do |n| pow = 2 ** (2 ** n) print "#{n}:\t" puts (1..).step(2).detect{|k| OpenSSL::BN.new(pow-k).prime?} end
Unbias a random generator
Ruby
Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1. ;Task details: * Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. * Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. * For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
def rand_n(bias) rand(bias) == 0 ? 1 : 0 end def unbiased(bias) a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0 a end runs = 1_000_000 keys = %i(bias biased unbiased) #use [:bias,:biased,:unbiased] in Ruby < 2.0 puts keys.join("\t") (3..6).each do |bias| counter = Hash.new(0) # counter will respond with 0 when key is not known runs.times do counter[:biased] += 1 if rand_n(bias) == 1 #the first time, counter has no key for :biased, so it will respond 0 counter[:unbiased] += 1 if unbiased(bias) == 1 end counter[:bias] = bias puts counter.values_at(*keys).join("\t") end
Unicode strings
Ruby
As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? ;Task: Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics: :* How easy is it to present Unicode strings in source code? :* Can Unicode literals be written directly, or be part of identifiers/keywords/etc? :* How well can the language communicate with the rest of the world? :* Is it good at input/output with Unicode? :* Is it convenient to manipulate Unicode strings in the language? :* How broad/deep does the language support Unicode? :* What encodings (e.g. UTF-8, UTF-16, etc) can be used? :* Does it support normalization? ;Note: This task is a bit unusual in that it encourages general discussion rather than clever coding. ;See also: * [[Unicode variable names]] * [[Terminal control/Display an extended character]]
p bad = "¿como\u0301 esta\u0301s?" # => "¿comó estás?" p bad.unicode_normalized? # => false p bad.unicode_normalize! # => "¿comó estás?" p bad.unicode_normalized? # => true
Universal Turing machine
Ruby
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936-1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. ;Task: Simulate such a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. '''Simple incrementer''' * '''States:''' q0, qf * '''Initial state:''' q0 * '''Terminating states:''' qf * '''Permissible symbols:''' B, 1 * '''Blank symbol:''' B * '''Rules:''' ** (q0, 1, 1, right, q0) ** (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 '''Three-state busy beaver''' * '''States:''' a, b, c, halt * '''Initial state:''' a * '''Terminating states:''' halt * '''Permissible symbols:''' 0, 1 * '''Blank symbol:''' 0 * '''Rules:''' ** (a, 0, 1, right, b) ** (a, 1, 1, left, c) ** (b, 0, 1, left, a) ** (b, 1, 1, right, b) ** (c, 0, 1, left, b) ** (c, 1, 1, stay, halt) The input for this machine should be an empty tape. '''Bonus:''' '''5-state, 2-symbol probable Busy Beaver machine from Wikipedia''' * '''States:''' A, B, C, D, E, H * '''Initial state:''' A * '''Terminating states:''' H * '''Permissible symbols:''' 0, 1 * '''Blank symbol:''' 0 * '''Rules:''' ** (A, 0, 1, right, B) ** (A, 1, 1, left, C) ** (B, 0, 1, right, C) ** (B, 1, 1, right, B) ** (C, 0, 1, right, D) ** (C, 1, 0, left, E) ** (D, 0, 1, left, A) ** (D, 1, 1, left, D) ** (E, 0, 1, stay, H) ** (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
class Turing class Tape def initialize(symbols, blank, starting_tape) @symbols = symbols @blank = blank @tape = starting_tape @index = 0 end def read retval = @tape[@index] unless retval retval = @tape[@index] = @blank end raise "invalid symbol '#{retval}' on tape" unless @tape.member?(retval) return retval end def write(symbol) @tape[@index] = symbol end def right @index += 1 end def left if @index == 0 @tape.unshift @blank else @index -= 1 end end def stay # nop end def get_tape return @tape end end def initialize(symbols, blank, initial_state, halt_states, running_states, rules, starting_tape = []) @tape = Tape.new(symbols, blank, starting_tape) @initial_state = initial_state @halt_states = halt_states @running_states = running_states @rules = rules @halted = false end def run raise "machine already halted" if @halted state = @initial_state while (true) break if @halt_states.member? state raise "unknown state '#{state}'" unless @running_states.member? state symbol = @tape.read outsym, action, state = @rules[state][symbol] @tape.write outsym @tape.send action end @halted = true return @tape.get_tape end end
Validate International Securities Identification Number
Ruby
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. ;Task: Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format, ''and'' the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. ;Details: The format of an ISIN is as follows: +------------- a 2-character ISO country code (A-Z) | +----------- a 9-character security code (A-Z, 0-9) | | +-- a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: # '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103. # '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.) ;Test cases: :::: {| class="wikitable" ! ISIN ! Validity ! Comment |- | US0378331005 || valid || |- | US0373831005 || not valid || The transposition typo is caught by the checksum constraint. |- | U50378331005 || not valid || The substitution typo is caught by the format constraint. |- | US03378331005 || not valid || The duplication typo is caught by the format constraint. |- | AU0000XVGZA3 || valid || |- | AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint. |- | FR0000988040 || valid || |} (The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.) Related task: * [[Luhn test of credit card numbers]] ;Also see: * Interactive online ISIN validator * Wikipedia article: International Securities Identification Number
RE = /\A[A-Z]{2}[A-Z0-9]{9}[0-9]{1}\z/ def valid_isin?(str) return false unless str =~ RE luhn(str.chars.map{|c| c.to_i(36)}.join) end p %w(US0378331005 US0373831005 U50378331005 US03378331005 AU0000XVGZA3 AU0000VXGZA3 FR0000988040).map{|tc| valid_isin?(tc) } # => [true, false, false, false, true, true, true]
Van Eck sequence
Ruby
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. ;Example: Using A: :0 Using B: :0 0 Using C: :0 0 1 Using B: :0 0 1 0 Using C: (zero last occurred two steps back - before the one) :0 0 1 0 2 Using B: :0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) :0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) :0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) :0 0 1 0 2 0 2 2 1 6 ... ;Task: # Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. # Use it to display here, on this page: :# The first ten terms of the sequence. :# Terms 991 - to - 1000 of the sequence. ;References: * Don't Know (the Van Eck Sequence) - Numberphile video. * Wikipedia Article: Van Eck's Sequence. * OEIS sequence: A181391.
van_eck = Enumerator.new do |y| ar = [0] loop do y << (term = ar.last) # yield ar << (ar.count(term)==1 ? 0 : ar.size - 1 - ar[0..-2].rindex(term)) end end ve = van_eck.take(1000) p ve.first(10), ve.last(10)
Van der Corput sequence
Ruby
When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 \times 2^1 + 0 \times 2^0. You can also have binary digits to the right of the "point", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. The weight for the second column to the right of the point is 2^{-2} or 1/4. And so on. If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4. Monte Carlo simulations. This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. '''Hint''' A ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 1\times 2^0. Reflected this would become .1101 or 1\times 2^{-1} + 1\times 2^{-2} + 0\times 2^{-3} + 1\times 2^{-4} ;Task description: * Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2. * Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0). * As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. ;See also: * The Basic Low Discrepancy Sequences * [[Non-decimal radices/Convert]] * Van der Corput sequence
def vdc(n, base=2) str = n.to_s(base).reverse str.to_i(base).quo(base ** str.length) end (2..5).each do |base| puts "Base #{base}: " + Array.new(10){|i| vdc(i,base)}.join(", ") end
Vector products
Ruby
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). If you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: * '''The dot product''' (a scalar quantity) :::: A * B = a1b1 + a2b2 + a3b3 * '''The cross product''' (a vector quantity) :::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) * '''The scalar triple product''' (a scalar quantity) :::: A * (B x C) * '''The vector triple product''' (a vector quantity) :::: A x (B x C) ;Task: Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) # Create a named function/subroutine/method to compute the dot product of two vectors. # Create a function to compute the cross product of two vectors. # Optionally create a function to compute the scalar triple product of three vectors. # Optionally create a function to compute the vector triple product of three vectors. # Compute and display: a * b # Compute and display: a x b # Compute and display: a * (b x c), the scalar triple product. # Compute and display: a x (b x c), the vector triple product. ;References: * A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}. * Wikipedia dot product. * Wikipedia cross product. * Wikipedia triple product. ;Related tasks: * [[Dot product]] * [[Quaternion type]]
require 'matrix' class Vector def scalar_triple_product(b, c) self.inner_product(b.cross_product c) end def vector_triple_product(b, c) self.cross_product(b.cross_product c) end end a = Vector[3, 4, 5] b = Vector[4, 3, 5] c = Vector[-5, -12, -13] puts "a dot b = #{a.inner_product b}" puts "a cross b = #{a.cross_product b}" puts "a dot (b cross c) = #{a.scalar_triple_product b, c}" puts "a cross (b cross c) = #{a.vector_triple_product b, c}"
Visualize a tree
Ruby
A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as: :::* indented text (a la unix tree command) :::* nested HTML tables :::* hierarchical GUI widgets :::* 2D or 3D images :::* etc. ;Task: Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]
Vogel's approximation method
Ruby
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them "A", "B", "C", "D", and "E". They estimate that: * A will require 30 hours of work, * B will require 20 hours of work, * C will require 70 hours of work, * D will require 30 hours of work, and * E will require 60 hours of work. They have identified 4 contractors willing to do the work, called "W", "X", "Y", and "Z". * W has 50 hours available to commit to working, * X has 60 hours available, * Y has 50 hours available, and * Z has 50 hours available. The cost per hour for each contractor for each task is summarized by the following table: A B C D E W 16 16 13 22 17 X 14 14 13 19 15 Y 19 19 20 23 50 Z 50 12 50 15 11 The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: :Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply A B C D E W X Y Z 1 2 2 0 4 4 3 1 0 1 E-Z(50) Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working. Repeat until all supply and demand is met: 2 2 2 0 3 2 3 1 0 - C-W(50) 3 5 5 7 4 35 - 1 0 - E-X(10) 4 5 5 7 4 - - 1 0 - C-X(20) 5 5 5 - 4 - - 0 0 - A-X(30) 6 - 19 - 23 - - - 4 - D-Y(30) - - - - - - - - - B-Y(20) Finally calculate the cost of your solution. In the example given it is PS3100: A B C D E W 50 X 30 20 10 Y 20 30 Z 50 The optimal solution determined by GLPK is PS3100: A B C D E W 50 X 10 20 20 10 Y 20 30 Z 50 ;Cf. * Transportation problem
# VAM # # Nigel_Galloway # September 1st., 2013 COSTS = {W: {A: 16, B: 16, C: 13, D: 22, E: 17}, X: {A: 14, B: 14, C: 13, D: 19, E: 15}, Y: {A: 19, B: 19, C: 20, D: 23, E: 50}, Z: {A: 50, B: 12, C: 50, D: 15, E: 11}} demand = {A: 30, B: 20, C: 70, D: 30, E: 60} supply = {W: 50, X: 60, Y: 50, Z: 50} COLS = demand.keys res = {}; COSTS.each_key{|k| res[k] = Hash.new(0)} g = {}; supply.each_key{|x| g[x] = COSTS[x].keys.sort_by{|g| COSTS[x][g]}} demand.each_key{|x| g[x] = COSTS.keys.sort_by{|g| COSTS[g][x]}} until g.empty? d = demand.collect{|x,y| [x, z = COSTS[g[x][0]][x], g[x][1] ? COSTS[g[x][1]][x] - z : z]} dmax = d.max_by{|n| n[2]} d = d.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]} s = supply.collect{|x,y| [x, z = COSTS[x][g[x][0]], g[x][1] ? COSTS[x][g[x][1]] - z : z]} dmax = s.max_by{|n| n[2]} s = s.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]} t,f = d[2]==s[2] ? [s[1], d[1]] : [d[2],s[2]] d,s = t > f ? [d[0],g[d[0]][0]] : [g[s[0]][0],s[0]] v = [supply[s], demand[d]].min res[s][d] += v demand[d] -= v if demand[d] == 0 then supply.reject{|k, n| n == 0}.each_key{|x| g[x].delete(d)} g.delete(d) demand.delete(d) end supply[s] -= v if supply[s] == 0 then demand.reject{|k, n| n == 0}.each_key{|x| g[x].delete(s)} g.delete(s) supply.delete(s) end end COLS.each{|n| print "\t", n} puts cost = 0 COSTS.each_key do |g| print g, "\t" COLS.each do |n| y = res[g][n] print y if y != 0 cost += y * COSTS[g][n] print "\t" end puts end print "\n\nTotal Cost = ", cost
Voronoi diagram
Ruby
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''. ;Task: Demonstrate how to generate and display a Voroni diagram. See algo [[K-means++ clustering]].
# frozen_string_literal: true require_relative 'raster_graphics' class ColourPixel < Pixel def initialize(x, y, colour) @colour = colour super x, y end attr_accessor :colour def distance_to(px, py) Math.hypot(px - x, py - y) end end width = 300 height = 200 npoints = 20 pixmap = Pixmap.new(width, height) @bases = npoints.times.collect do |_i| ColourPixel.new( 3 + rand(width - 6), 3 + rand(height - 6), # provide a margin to draw a circle RGBColour.new(rand(256), rand(256), rand(256)) ) end pixmap.each_pixel do |x, y| nearest = @bases.min_by { |base| base.distance_to(x, y) } pixmap[x, y] = nearest.colour end @bases.each do |base| pixmap[base.x, base.y] = RGBColour::BLACK pixmap.draw_circle(base, 2, RGBColour::BLACK) end pixmap.save_as_png('voronoi_rb.png')
Wagstaff primes
Ruby
Definition A ''Wagstaff prime'' is a prime number of the form ''(2^p + 1)/3'' where the exponent ''p'' is an odd prime. ;Example (2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes. ;Task Find and show here the first ''10'' Wagstaff primes and their corresponding exponents ''p''. ;Stretch (requires arbitrary precision integers) Find and show here the exponents ''p'' corresponding to the next ''14'' Wagstaff primes (not the primes themselves) and any more that you have the patience for. When testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty. ;Note It can be shown (see talk page) that ''(2^p + 1)/3'' is always integral if ''p'' is odd. So there's no need to check for that prior to checking for primality. ;References * Wikipedia - Wagstaff prime * OEIS:A000979 - Wagstaff primes
require 'prime' require 'gmp' wagstaffs = Enumerator.new do |y| odd_primes = Prime.each odd_primes.next #skip 2 loop do p = odd_primes.next candidate = (2 ** p + 1)/3 y << [p, candidate] unless GMP::Z.new(candidate).probab_prime?.zero? end end 10.times{puts "%5d - %s" % wagstaffs.next} 14.times{puts "%5d" % wagstaffs.next.first}
Water collected between towers
Ruby
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ## 9 ## 8 ## 8 ## 7 ## ## 7 #### 6 ## ## ## 6 ###### 5 ## ## ## #### 5 ########## 4 ## ## ######## 4 ############ 3 ###### ######## 3 ############## 2 ################ ## 2 ################## 1 #################### 1 #################### In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series: [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] See, also: * Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele * Water collected between towers on Stack Overflow, from which the example above is taken) * An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
def a(array) n=array.length left={} right={} left[0]=array[0] i=1 loop do break if i >=n left[i]=[left[i-1],array[i]].max i += 1 end right[n-1]=array[n-1] i=n-2 loop do break if i<0 right[i]=[right[i+1],array[i]].max i-=1 end i=0 water=0 loop do break if i>=n water+=[left[i],right[i]].min-array[i] i+=1 end puts water end a([ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ]) a([ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ]) a([ 5, 5, 5, 5 ]) a([ 5, 6, 7, 8 ]) a([ 8, 7, 7, 6 ]) a([ 6, 7, 10, 7, 6 ]) return
Weird numbers
Ruby
In number theory, a perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect''). For example: * '''12''' is ''not'' a weird number. ** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12), ** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''. * '''70''' ''is'' a weird number. ** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70), ** and there is no subset of proper divisors that sum to '''70'''. ;Task: Find and display, here on this page, the first '''25''' weird numbers. ;Related tasks: :* Abundant, deficient and perfect number classifications :* Proper divisors ;See also: :* OEIS: A006037 weird numbers :* Wikipedia: weird number :* MathWorld: weird number
def divisors(n) divs = [1] divs2 = [] i = 2 while i * i <= n if n % i == 0 then j = (n / i).to_i divs.append(i) if i != j then divs2.append(j) end end i = i + 1 end divs2 += divs.reverse return divs2 end def abundant(n, divs) return divs.sum > n end def semiperfect(n, divs) if divs.length > 0 then h = divs[0] t = divs[1..-1] if n < h then return semiperfect(n, t) else return n == h || semiperfect(n - h, t) || semiperfect(n, t) end else return false end end def sieve(limit) w = Array.new(limit, false) i = 2 while i < limit if not w[i] then divs = divisors(i) if not abundant(i, divs) then w[i] = true elsif semiperfect(i, divs) then j = i while j < limit w[j] = true j = j + i end end end i = i + 2 end return w end def main w = sieve(17000) count = 0 max = 25 print "The first %d weird numbers:\n" % [max] n = 2 while count < max if not w[n] then print n, " " count = count + 1 end n = n + 2 end print "\n" end main()
Word frequency
Ruby
Given a text file and an integer '''n''', print/display the '''n''' most common words in the file (and the number of their occurrences) in decreasing frequency. For the purposes of this task: * A word is a sequence of one or more contiguous letters. * You are free to define what a ''letter'' is. * Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion. * You may treat a compound word like '''well-dressed''' as either one word or two. * The word '''it's''' could also be one or two words as you see fit. * You may also choose not to support non US-ASCII characters. * Assume words will not span multiple lines. * Don't worry about normalization of word spelling differences. * Treat '''color''' and '''colour''' as two distinct words. * Uppercase letters are considered equivalent to their lowercase counterparts. * Words of equal frequency can be listed in any order. * Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words. ;History: This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). ;References: *McIlroy's program
class String def wc n = Hash.new(0) downcase.scan(/[A-Za-zÀ-ÿ]+/) { |g| n[g] += 1 } n.sort{|n,g| n[1]<=>g[1]} end end open('135-0.txt') { |n| n.read.wc[-10,10].each{|n| puts n[0].to_s+"->"+n[1].to_s} }
Word frequency
Ruby 2.7
Given a text file and an integer '''n''', print/display the '''n''' most common words in the file (and the number of their occurrences) in decreasing frequency. For the purposes of this task: * A word is a sequence of one or more contiguous letters. * You are free to define what a ''letter'' is. * Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion. * You may treat a compound word like '''well-dressed''' as either one word or two. * The word '''it's''' could also be one or two words as you see fit. * You may also choose not to support non US-ASCII characters. * Assume words will not span multiple lines. * Don't worry about normalization of word spelling differences. * Treat '''color''' and '''colour''' as two distinct words. * Uppercase letters are considered equivalent to their lowercase counterparts. * Words of equal frequency can be listed in any order. * Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words. ;History: This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). ;References: *McIlroy's program
RE = /[[:alpha:]]+/ count = open("135-0.txt").read.downcase.scan(RE).tally.max_by(10, &:last) count.each{|ar| puts ar.join("->") }
Word ladder
Ruby from Raku
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice.
require "set" Words = File.open("unixdict.txt").read.split("\n"). group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }. to_h def word_ladder(from, to) raise "Length mismatch" unless from.length == to.length sized_words = Words[from.length] work_queue = [[from]] used = Set.new [from] while work_queue.length > 0 new_q = [] work_queue.each do |words| last_word = words[-1] new_tails = Enumerator.new do |enum| ("a".."z").each do |replacement_letter| last_word.length.times do |i| new_word = last_word.clone new_word[i] = replacement_letter next unless sized_words.include? new_word and not used.include? new_word enum.yield new_word used.add new_word return words + [new_word] if new_word == to end end end new_tails.each do |t| new_q.push(words + [t]) end end work_queue = new_q end end [%w<boy man>, %w<girl lady>, %w<john jane>, %w<child adult>].each do |from, to| if ladder = word_ladder(from, to) puts ladder.join " → " else puts "#{from} into #{to} cannot be done" end end
Word wrap
Ruby
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. ;Basic task: The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. ;Extra credit: Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you ''must reference documentation'' indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results.
class String def wrap(width) txt = gsub("\n", " ") para = [] i = 0 while i < length j = i + width j -= 1 while j != txt.length && j > i + 1 && !(txt[j] =~ /\s/) para << txt[i ... j] i = j + 1 end para end end text = <<END In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything. END [72,80].each do |w| puts "." * w puts text.wrap(w) end
World Cup group stage
Ruby
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. :::* A win is worth three points. :::* A draw/tie is worth one point. :::* A loss is worth zero points. ;Task: :* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. :* Calculate the standings points for each team with each combination of outcomes. :* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". ''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''
teams = [:a, :b, :c, :d] matches = teams.combination(2).to_a outcomes = [:win, :draw, :loss] gains = {win:[3,0], draw:[1,1], loss:[0,3]} places_histogram = Array.new(4) {Array.new(10,0)} # The Array#repeated_permutation method generates the 3^6 different # possible outcomes outcomes.repeated_permutation(6).each do |outcome| results = Hash.new(0) # combine this outcomes with the matches, and generate the points table outcome.zip(matches).each do |decision, (team1, team2)| results[team1] += gains[decision][0] results[team2] += gains[decision][1] end # accumulate the results results.values.sort.reverse.each_with_index do |points, place| places_histogram[place][points] += 1 end end fmt = "%s :" + "%4s"*10 puts fmt % [" ", *0..9] puts fmt % ["-", *["---"]*10] places_histogram.each.with_index(1) {|hist,place| puts fmt % [place, *hist]}
Write float arrays to a text file
Ruby
Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
# prepare test data x = [1, 2, 3, 1e11] y = x.collect { |xx| Math.sqrt xx } xprecision = 3 yprecision = 5 # write the arrays open('sqrt.dat', 'w') do |f| x.zip(y) { |xx, yy| f.printf("%.*g\t%.*g\n", xprecision, xx, yprecision, yy) } end # print the result file open('sqrt.dat', 'r') { |f| puts f.read }
Write language name in 3D ASCII
Ruby
Write/display a language's name in '''3D''' ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) ;Related tasks: * draw a sphere * draw a cuboid * draw a rotating cube * draw a Deathstar
text = <<EOS #### # # # # # # # #### # # ### # # # # # # # # # # # # # # # # # # # ### ### # # # EOS def banner3D_1(text, shift=-1) txt = text.each_line.map{|line| line.gsub('#','__/').gsub(' ',' ')} offset = Array.new(txt.size){|i| " " * shift.abs * i} offset.reverse! if shift < 0 puts offset.zip(txt).map(&:join) end banner3D_1(text) puts # Other display: def banner3D_2(text, shift=-2) txt = text.each_line.map{|line| line.chomp + ' '} offset = txt.each_index.map{|i| " " * shift.abs * i} offset.reverse! if shift < 0 txt.each_with_index do |line,i| line2 = offset[i] + line.gsub(' ',' ').gsub('#','///').gsub('/ ','/\\') puts line2, line2.tr('/\\\\','\\\\/') end end banner3D_2(text) puts # Another display: def banner3D_3(text) txt = text.each_line.map(&:rstrip) offset = [*0...txt.size].reverse area = Hash.new(' ') box = [%w(/ / / \\), %w(\\ \\ \\ /)] txt.each_with_index do |line,i| line.each_char.with_index do |c,j| next if c==' ' x = offset[i] + 2*j box[0].each_with_index{|c,k| area[[x+k,i ]] = c} box[1].each_with_index{|c,k| area[[x+k,i+1]] = c} end end (xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax) puts (ymin..ymax).map{|y| (xmin..xmax).map{|x| area[[x,y]]}.join} end banner3D_3 <<EOS #### # # # # # # # # # # #### # # #### # # # # # # # # # # # # # # # # # # # # # # # # # # # ### #### # # # EOS
Yellowstone sequence
Ruby
The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence. ;Example: a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2). ;Task : Find and show as output the first '''30''' Yellowstone numbers. ;Extra : Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers. ;Related tasks: :* Greatest common divisor. :* Plot coordinate pairs. ;See also: :* The OEIS entry: A098550 The Yellowstone permutation. :* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].
def yellow(n) a = [1, 2, 3] b = { 1 => true, 2 => true, 3 => true } i = 4 while n > a.length if !b[i] && i.gcd(a[-1]) == 1 && i.gcd(a[-2]) > 1 a << i b[i] = true i = 4 end i += 1 end a end p yellow(30)
Zeckendorf number representation
Ruby
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution. ;Task: Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. ;Also see: * OEIS A014417 for the the sequence of required results. * Brown's Criterion - Numberphile ;Related task: * [[Fibonacci sequence]]
def zeckendorf return to_enum(__method__) unless block_given? x = 0 loop do bin = x.to_s(2) yield bin unless bin.include?("11") x += 1 end end zeckendorf.take(21).each_with_index{|x,i| puts "%3d: %8s"% [i, x]}
Zeckendorf number representation
Ruby from Python
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution. ;Task: Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. ;Also see: * OEIS A014417 for the the sequence of required results. * Brown's Criterion - Numberphile ;Related task: * [[Fibonacci sequence]]
def zeckendorf(n) return 0 if n.zero? fib = [1,2] fib << fib[-2] + fib[-1] while fib[-1] < n dig = "" fib.reverse_each do |f| if f <= n dig, n = dig + "1", n - f else dig += "0" end end dig.to_i end for i in 0..20 puts '%3d: %8d' % [i, zeckendorf(i)] end
Zeckendorf number representation
Ruby from Crystal
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution. ;Task: Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. ;Also see: * OEIS A014417 for the the sequence of required results. * Brown's Criterion - Numberphile ;Related task: * [[Fibonacci sequence]]
def zeckendorf(n) 0.step.lazy.map { |x| x.to_s(2) }.reject { |z| z.include?("11") }.first(n) end zeckendorf(21).each_with_index{ |x,i| puts "%3d: %8s"% [i, x] }
Zero to the zero power
Ruby
Some computer programming languages are not exactly consistent (with other computer programming languages) when ''raising zero to the zeroth power'': 00 ;Task: Show the results of raising zero to the zeroth power. If your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like: x = 0 y = 0 z = x**y say 'z=' z '''Show the result here.''' And of course use any symbols or notation that is supported in your computer programming language for exponentiation. ;See also: * The Wiki entry: Zero to the power of zero. * The Wiki entry: Zero to the power of zero: History. * The MathWorld(tm) entry: exponent laws. ** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1. * The OEIS entry: The special case of zero to the zeroth power
require 'bigdecimal' [0, 0.0, Complex(0), Rational(0), BigDecimal("0")].each do |n| printf "%10s: ** -> %s\n" % [n.class, n**n] end
Zhang-Suen thinning algorithm
Ruby
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### ;Algorithm: Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as: P9 P2 P3 P8 P1 P4 P7 P6 P5 Obviously the boundary pixels of the image cannot have the full eight neighbours. * Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). * Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) ;Step 1: All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. * (0) The pixel is black and has eight neighbours * (1) 2 <= B(P1) <= 6 * (2) A(P1) = 1 * (3) At least one of P2 and P4 and P6 is white * (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. ;Step 2: All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. * (0) The pixel is black and has eight neighbours * (1) 2 <= B(P1) <= 6 * (2) A(P1) = 1 * (3) At least one of P2 and P4 and '''P8''' is white * (4) At least one of '''P2''' and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. ;Iteration: If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. ;Task: # Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. # Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 ;Reference: * Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. * "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
class ZhangSuen NEIGHBOUR8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] # 8 neighbors CIRCULARS = NEIGHBOUR8 + [NEIGHBOUR8.first] # P2, ... P9, P2 def initialize(str, black="#") s1 = str.each_line.map{|line| line.chomp.each_char.map{|c| c==black ? 1 : 0}} s2 = s1.map{|line| line.map{0}} xrange = 1 ... s1.size-1 yrange = 1 ... s1[0].size-1 printout(s1) begin @r = 0 xrange.each{|x| yrange.each{|y| s2[x][y] = s1[x][y] - zs(s1,x,y,1)}} # Step 1 xrange.each{|x| yrange.each{|y| s1[x][y] = s2[x][y] - zs(s2,x,y,0)}} # Step 2 end until @r == 0 printout(s1) end def zs(ng,x,y,g) return 0 if ng[x][y] == 0 or # P1 (ng[x-1][y] + ng[x][y+1] + ng[x+g][y-1+g]) == 3 or # P2, P4, P6/P8 (ng[x-1+g][y+g] + ng[x+1][y] + ng[x][y-1]) == 3 # P4/P2, P6, P8 bp1 = NEIGHBOUR8.inject(0){|res,(i,j)| res += ng[x+i][y+j]} # B(P1) return 0 if bp1 < 2 or 6 < bp1 ap1 = CIRCULARS.map{|i,j| ng[x+i][y+j]}.each_cons(2).count{|a,b| a<b} # A(P1) return 0 if ap1 != 1 @r = 1 end def printout(image) puts image.map{|row| row.map{|col| " #"[col]}.join} end end str = <<EOS ........................................................... .#################...................#############......... .##################...............################......... .###################............##################......... .########.....#######..........###################......... ...######.....#######.........#######.......######......... ...######.....#######........#######....................... ...#################.........#######....................... ...################..........#######....................... ...#################.........#######....................... ...######.....#######........#######....................... ...######.....#######........#######....................... ...######.....#######.........#######.......######......... .########.....#######..........###################......... .########.....#######.######....##################.######.. .########.....#######.######......################.######.. .########.....#######.######.........#############.######.. ........................................................... EOS ZhangSuen.new(str) task_example = <<EOS 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 EOS ZhangSuen.new(task_example, "1")