title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Numbers with equal rises and falls
Ruby
When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right). ;Definition: Given the decimal digits of the number are written as a series d: :* A ''rise'' is an index i such that d(i) < d(i+1) :* A ''fall'' is an index i such that d(i) > d(i+1) ;Examples: :* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence. :* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence. ;Task: :* Print the first '''200''' numbers in the sequence :* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002''' ;See also: * OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls". ;Related tasks: * Esthetic numbers
class Integer def eq_rise_fall? = digits.each_cons(2).sum{|a,b| a <=> b} == 0 end puts (1..).lazy.select(&:eq_rise_fall?).take(200).force.join(" ") n = 10_000_000 res = (1..).lazy.select(&:eq_rise_fall?).take(n).drop(n-1).first puts "The #{n}th number in the sequence is #{res}."
Numeric error propagation
Ruby
If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; then if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, then sf can be calculated as follows: :;Addition/Subtraction :* If f = a +- c, or f = c +- a then '''sf = sa''' :* If f = a +- b then '''sf2 = sa2 + sb2''' :;Multiplication/Division :* If f = ca or f = ac then '''sf = |csa|''' :* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)''' :;Exponentiation :* If f = ac then '''sf = |fc(sa / a)|''' Caution: ::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue. ;Task details: # Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. # Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2 # Print and display both '''d''' and its error. ;References: * A Guide to Error Propagation B. Keeney, 2005. * Propagation of uncertainty Wikipedia. ;Related task: * [[Quaternion type]]
class NumberWithUncertainty def initialize(number, error) @num = number @err = error.abs end attr_reader :num, :err def +(other) if other.kind_of?(self.class) self.class.new(num + other.num, Math::hypot(err, other.err)) else self.class.new(num + other, err) end end def -(other) if other.kind_of?(self.class) self.class.new(num - other.num, Math::hypot(err, other.err)) else self.class.new(num - other, err) end end def *(other) if other.kind_of?(self.class) prod = num * other.num e = Math::hypot((prod * err / num), (prod * other.err / other.num)) self.class.new(prod, e) else self.class.new(num * other, (err * other).abs) end end def /(other) if other.kind_of?(self.class) quo = num / other.num e = Math::hypot((quo * err / num), (quo * other.err / other.num)) self.class.new(quo, e) else self.class.new(num / other, (err * other).abs) end end def **(exponent) Float(exponent) rescue raise ArgumentError, "not an number: #{exponent}" prod = num ** exponent self.class.new(prod, (prod * exponent * err / num).abs) end def sqrt self ** 0.5 end def to_s "#{num} \u00b1 #{err}" end end x1 = NumberWithUncertainty.new(100, 1.1) y1 = NumberWithUncertainty.new( 50, 1.2) x2 = NumberWithUncertainty.new(200, 2.2) y2 = NumberWithUncertainty.new(100, 2.3) puts ((x1 - x2) ** 2 + (y1 - y2) ** 2).sqrt
Odd word problem
Ruby
Write a program that solves the odd word problem with the restrictions given below. ;Description: You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: * the words (sequence of consecutive letters) are delimited by one and only one punctuation, * the stream will begin with a word, * the words will be at least one letter long, and * a full stop (a period, [.]) appears after, and only after, the last word. ;Example: A stream with six words: :: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: :: what,si,the;gninaem,of:efil. while observing the following restrictions: # Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; # You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; # You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. ;Test cases: Work on both the "life" example given above, and also the text: :: we,are;not,in,kansas;any,more.
These Ruby programs store each character in a single-character string. ===Using fibers and recursion===
Odd word problem
Ruby 1.9
Write a program that solves the odd word problem with the restrictions given below. ;Description: You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: * the words (sequence of consecutive letters) are delimited by one and only one punctuation, * the stream will begin with a word, * the words will be at least one letter long, and * a full stop (a period, [.]) appears after, and only after, the last word. ;Example: A stream with six words: :: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: :: what,si,the;gninaem,of:efil. while observing the following restrictions: # Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; # You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; # You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. ;Test cases: Work on both the "life" example given above, and also the text: :: we,are;not,in,kansas;any,more.
f, r = nil fwd = proc {|c| c =~ /[[:alpha:]]/ ? [(print c), fwd[Fiber.yield f]][1] : c } rev = proc {|c| c =~ /[[:alpha:]]/ ? [rev[Fiber.yield r], (print c)][0] : c } (f = Fiber.new { loop { print fwd[Fiber.yield r] }}).resume (r = Fiber.new { loop { print rev[Fiber.yield f] }}).resume coro = f until $stdin.eof? coro = coro.resume($stdin.getc) end
Old Russian measure of length
Ruby
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''. ;Also see: :* Old Russian measure of length
module Distances RATIOS = {arshin: 0.7112, centimeter: 0.01, diuym: 0.0254, fut: 0.3048, kilometer: 1000.0, liniya: 0.00254, meter: 1.0, milia: 7467.6, piad: 0.1778, sazhen: 2.1336, tochka: 0.000254, vershok: 0.04445, versta: 1066.8} def self.method_missing(meth, arg) from, to = meth.to_s.split("2").map(&:to_sym) raise NoMethodError, meth if ([from,to]-RATIOS.keys).size > 0 RATIOS[from] * arg / RATIOS[to] end def self.print_others(name, num) puts "#{num} #{name} =" RATIOS.except(name.to_sym).each {|k,v| puts "#{ (1.0 / v*num)} #{k}" } end end Distances.print_others("meter", 2) puts p Distances.meter2centimeter(3) p Distances.arshin2meter(1) p Distances.versta2kilometer(20) # en Hoeperdepoep zat op de stoep # 13*13 = 169 methods supported, but not: p Distances.mile2piad(1)
Old lady swallowed a fly
Ruby
Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
descriptions = { :fly => "I don't know why S", :spider => "That wriggled and jiggled and tickled inside her.", :bird => "Quite absurd T", :cat => "Fancy that, S", :dog => "What a hog, S", :goat => "She opened her throat T", :cow => "I don't know how S", :horse => "She's dead, of course.", } animals = descriptions.keys animals.each_with_index do |animal, idx| puts "There was an old lady who swallowed a #{animal}." d = descriptions[animal] case d[-1] when "S" then d[-1] = "she swallowed a #{animal}." when "T" then d[-1] = "to swallow a #{animal}." end puts d break if animal == :horse idx.downto(1) do |i| puts "She swallowed the #{animals[i]} to catch the #{animals[i-1]}." case animals[i-1] when :spider, :fly then puts descriptions[animals[i-1]] end end print "Perhaps she'll die.\n\n" end
One of n lines in a file
Ruby
A method of choosing a line randomly from a file: ::* Without reading the file more than once ::* When substantial parts of the file cannot be held in memory ::* Without knowing how many lines are in the file Is to: ::* keep the first line of the file as a possible choice, then ::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. ::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ::* ... ::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N ::* Return the computed possible choice when no further lines exist in the file. ;Task: # Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. # Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times. # Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
# Returns a random line from _io_, or nil if _io_ has no lines. # # Get a random line from /etc/passwd # line = open("/etc/passwd") {|f| random_line(f) } def random_line(io) choice = io.gets; count = 1 while line = io.gets rand(count += 1).zero? and choice = line end choice end def one_of_n(n) # Create a mock IO that provides line numbers instead of lines. # Assumes that #random_line calls #gets. (mock_io = Object.new).instance_eval do @count = 0 @last = n def self.gets (@count < @last) ? (@count += 1) : nil end end random_line(mock_io) end chosen = Hash.new(0) 1_000_000.times { chosen[one_of_n(10)] += 1 } chosen.keys.sort.each do |key| puts "#{key} chosen #{chosen[key]} times" end
Operator precedence
Ruby
Operators in C and C++}} ;Task: Provide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
Ruby operators, by precedence (high to low), with arity (N), associativity (A), and definability (D) {| class="wikitable" ! Operator(s) || N || A || D || Operation |- | ! ~ + || 1 || R || Y || Boolean NOT, bitwise complement, unary plus |- | ** || 2 || R || Y || Exponentiation |- | - || 1 || R || Y || Unary minus (define with -@) |- | * / % || 2 || L || Y || Multiplication, division, modulo (remainder) |- | + - || 2 || L || Y || Addition (or concatenation), subtraction |- | << >> || 2 || L || Y || Bitwise shift-left (or append), bitwise shift-right |- | & || 2 || L || Y || Bitwise AND |- | <nowiki>|</nowiki> ^ || 2 || L || Y || Bitwise OR, bitwise XOR |- | < <= >= > || 2 || L || Y || Ordering |- | | == === != =~ !~ <=> || 2 || N || Y || Equality, pattern matching, comparison |- | && || 2 || L || N || Boolean AND |- | <nowiki>||</nowiki> || 2 || L || N || Boolean OR |- | .. ... || 2 || N || N || Range creation and Boolean flip-flops |- | ? : || 3 || R || N || Conditional |- | rescue || 2 || L || N || Exception-handling modifier |- | = **= *= / = %= += -= <<= >>= &&= &= ^= || 2 || R || N || Assignment |- | defined? || 1 || N || N || Test variable definition and type |- | not || 1 || R || N || Boolean NOT (low precedence) |- | and or || 2 || L || N || Boolean AND, Boolean OR (low precedence) |- | if unless while until || 2 || N || N || Conditional and loop modifiers |}
Padovan sequence
Ruby
The Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. ::{| class="wikitable" ! Comment !! Padovan !! Fibonacci |- | || || |- | Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci |- | || || |- | Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1 |- | Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2) |- | || || |- | First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34 |- | || || |- | Ratio of successive terms... || Plastic ratio, p || Golden ratio, g |- | || 1.324717957244746025960908854... || 1.6180339887498948482... |- | Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2 |- | Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1 |- | || || |- | Spirally tiling the plane using. || Equilateral triangles || Squares |- | || || |- | Constants for ... || s= 1.0453567932525329623 || a=5**0.5 |- | ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5) |- | || || |- | L-System Variables. || A,B,C || A,B |- | L-System Start/Axiom. || A || A |- | L-System Rules. || A->B,B->C,C->AB || A->B,B->AB |} ;Task: * Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation. * Write a function/method/subroutine to compute successive members of the Padovan series using the floor function. * Show the first twenty terms of the sequence. * Confirm that the recurrence and floor based functions give the same results for 64 terms, * Write a function/method/... using the L-system to generate successive strings. * Show the first 10 strings produced from the L-system * Confirm that the length of the first 32 strings produced is the Padovan sequence. Show output here, on this page. ;Ref: * The Plastic Ratio - Numberphile video.
padovan = Enumerator.new do |y| ar = [1, 1, 1] loop do ar << ar.first(2).sum y << ar.shift end end P, S = 1.324717957244746025960908854, 1.0453567932525329623 def padovan_f(n) = (P**(n-1) / S + 0.5).floor puts "Recurrence Padovan: #{padovan.take(20)}" puts "Floor function: #{(0...20).map{|n| padovan_f(n)}}" n = 63 bool = (0...n).map{|n| padovan_f(n)} == padovan.take(n) puts "Recurrence and floor function are equal upto #{n}: #{bool}." puts def l_system(axiom = "A", rules = {"A" => "B", "B" => "C", "C" => "AB"} ) return enum_for(__method__, axiom, rules) unless block_given? loop do yield axiom axiom = axiom.chars.map{|c| rules[c] }.join end end puts "First 10 elements of L-system: #{l_system.take(10).join(", ")} " n = 32 bool = l_system.take(n).map(&:size) == padovan.take(n) puts "Sizes of first #{n} l_system strings equal to recurrence padovan? #{bool}."
Palindrome dates
Ruby
Today ('''2020-02-02''', at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the '''yyyy-mm-dd''' format but, unusually, also for countries which use the '''dd-mm-yyyy''' format. ;Task Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.
require 'date' palindate = Enumerator.new do |yielder| ("2020"..).each do |y| m, d = y.reverse.scan(/../) # let the Y10K kids handle 5 digit years strings = [y, m, d] yielder << strings.join("-") if Date.valid_date?( *strings.map( &:to_i ) ) end end puts palindate.take(15)
Palindromic gapful numbers
Ruby from Crystal
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''1037''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''1037'''. A palindromic number is (for this task, a positive integer expressed in base ten), when the number is reversed, is the same as the original number. ;Task: :* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with: :::* the digit '''1''' :::* the digit '''2''' :::* the digit '''3''' :::* the digit '''4''' :::* the digit '''5''' :::* the digit '''6''' :::* the digit '''7''' :::* the digit '''8''' :::* the digit '''9''' :* Show (nine sets, like above) of palindromic gapful numbers: :::* the last '''15''' palindromic gapful numbers (out of '''100''') :::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional} For other ways of expressing the (above) requirements, see the ''discussion'' page. ;Note: All palindromic gapful numbers are divisible by eleven. ;Related tasks: :* palindrome detection. :* gapful numbers. ;Also see: :* The OEIS entry: A108343 gapful numbers.
class PalindromicGapfuls include Enumerable def initialize(digit) @digit = digit @nn = @digit * 11 # digit gapful divisor: 11, 22,...88, 99 end def each power = 1 # these two lines will work while power += 1 # for all Ruby VMs|versions #(2..).each do |power| # Ruby => 2.6; can replace above 2 lines base = 10**(power >> 1) # value of middle digit position: 10.. base11 = base * 11 # value of middle two digits positions: 110.. this_lo = base * @digit # starting half for this digit: 10.. to 90.. next_lo = base * (@digit + 1) # starting half for next digit: 20.. to 100.. this_lo.step(to: next_lo - 1, by: 10) do |front_half| # d_00; d_10; d_20; ... left_half = front_half.to_s; right_half = left_half.reverse if power.odd? palindrome = (left_half + right_half).to_i 10.times do yield palindrome if palindrome % @nn == 0 palindrome += base11 end else palindrome = (left_half.chop + right_half).to_i 10.times do yield palindrome if palindrome % @nn == 0 palindrome += base end end end end end # Optimized output method: only keep desired values. def keep_from(count, keep) to_skip = (count - keep) kept = [] each_with_index do |value, i| i < to_skip ? next : kept << value return kept if kept.size == keep end end end start = Time.now count, keep = 20, 20 puts "First 20 palindromic gapful numbers ending with:" 1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}" } count, keep = 100, 15 puts "\nLast 15 of first 100 palindromic gapful numbers ending in:" 1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}" } count, keep = 1_000, 10 puts "\nLast 10 of first 1000 palindromic gapful numbers ending in:" 1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}" } count, keep = 100_000, 1 puts "\n100,000th palindromic gapful number ending with:" 1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}" } count, keep = 1_000_000, 1 puts "\n1,000,000th palindromic gapful number ending with:" 1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}" } count, keep = 10_000_000, 1 puts "\n10,000,000th palindromic gapful number ending with:" 1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}" } puts (Time.now - start)
Palindromic gapful numbers
Ruby from F#
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''1037''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''1037'''. A palindromic number is (for this task, a positive integer expressed in base ten), when the number is reversed, is the same as the original number. ;Task: :* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with: :::* the digit '''1''' :::* the digit '''2''' :::* the digit '''3''' :::* the digit '''4''' :::* the digit '''5''' :::* the digit '''6''' :::* the digit '''7''' :::* the digit '''8''' :::* the digit '''9''' :* Show (nine sets, like above) of palindromic gapful numbers: :::* the last '''15''' palindromic gapful numbers (out of '''100''') :::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional} For other ways of expressing the (above) requirements, see the ''discussion'' page. ;Note: All palindromic gapful numbers are divisible by eleven. ;Related tasks: :* palindrome detection. :* gapful numbers. ;Also see: :* The OEIS entry: A108343 gapful numbers.
class PalNo def initialize(set) @set, @l=set, 3 end def fN(n) return [0,1,2,3,4,5,6,7,8,9] if n==1 return [0,11,22,33,44,55,66,77,88,99] if n==2 a=[]; [0,1,2,3,4,5,6,7,8,9].product(fN(n-2)).each{|g| a.push(g[0]*10**(n-1)+g[0]+10*g[1])}; return a end def each while true do fN(@l-2).each{|g| a=@set*10**(@l-1)+@set+10*g; yield a if a%(11*@set)==0}; @l+=1 end end end for n in 1..9 do palNo=PalNo.new(n); g=1; palNo.each{|n| print "#{n} "; g+=1; break unless g<21}; puts "" end; puts "####" for n in 1..9 do palNo=PalNo.new(n); g=1; palNo.each{|n| print "#{n} " if g>85; g+=1; break unless g<101}; puts "" end; puts "####" for n in 1..9 do palNo=PalNo.new(n); g=1; palNo.each{|n| print "#{n} " if g>990; g+=1; break unless g<1001}; puts "" end; puts "####"
Palindromic gapful numbers
Ruby from Ruby of F#
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''1037''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''1037'''. A palindromic number is (for this task, a positive integer expressed in base ten), when the number is reversed, is the same as the original number. ;Task: :* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with: :::* the digit '''1''' :::* the digit '''2''' :::* the digit '''3''' :::* the digit '''4''' :::* the digit '''5''' :::* the digit '''6''' :::* the digit '''7''' :::* the digit '''8''' :::* the digit '''9''' :* Show (nine sets, like above) of palindromic gapful numbers: :::* the last '''15''' palindromic gapful numbers (out of '''100''') :::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional} For other ways of expressing the (above) requirements, see the ''discussion'' page. ;Note: All palindromic gapful numbers are divisible by eleven. ;Related tasks: :* palindrome detection. :* gapful numbers. ;Also see: :* The OEIS entry: A108343 gapful numbers.
class PalNo def initialize(digit) @digit, @l, @dd = digit, 3, 11*digit end def fN(n) return [0,1,2,3,4,5,6,7,8,9] if n==1 return [0,11,22,33,44,55,66,77,88,99] if n==2 a=[]; [0,1,2,3,4,5,6,7,8,9].product(fN(n-2)).each{ |g0,g1| a << g0*10**(n-1)+g0+10*g1 }; return a end def show(count, keep) to_skip, palcnt, pals = count - keep, 0, [] while palcnt < count fN(@l-2).each{ |g| pal=@digit*10**(@l-1)+@digit+10*g; pals << pal if pal%(@dd)==0 && (palcnt += 1) > to_skip; break if palcnt - to_skip == keep }; @l+=1 end print pals; puts end end start = Time.now (1..9).each { |digit| PalNo.new(digit).show(20, 20) }; puts "####" (1..9).each { |digit| PalNo.new(digit).show(100, 15) }; puts "####" (1..9).each { |digit| PalNo.new(digit).show(1000, 10) }; puts "####" (1..9).each { |digit| PalNo.new(digit).show(100_000, 1) }; puts "####" (1..9).each { |digit| PalNo.new(digit).show(1_000_000, 1) }; puts "####" (1..9).each { |digit| PalNo.new(digit).show(10_000_000, 1) }; puts "####" puts (Time.now - start)
Pancake numbers
Ruby from C
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. [[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). ;References # Bill Gates and the pancake problem # A058986
def pancake(n) gap = 2 sum = 2 adj = -1 while sum < n adj = adj + 1 gap = gap * 2 - 1 sum = sum + gap end return n + adj end for i in 0 .. 3 for j in 1 .. 5 n = i * 5 + j print "p(%2d) = %2d " % [n, pancake(n)] end print "\n" end
Pangram checker
Ruby
A pangram is a sentence that contains all the letters of the English alphabet at least once. For example: ''The quick brown fox jumps over the lazy dog''. ;Task: Write a function or method to check a sentence to see if it is a pangram (or not) and show its use. ;Related tasks: :* determine if a string has all the same characters :* determine if a string has all unique characters
def pangram?(sentence) s = sentence.downcase ('a'..'z').all? {|char| s.include? (char) } end p pangram?('this is a sentence') # ==> false p pangram?('The quick brown fox jumps over the lazy dog.') # ==> true
Paraffins
Ruby from Python
This organic chemistry task is essentially to implement a tree enumeration algorithm. ;Task: Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with '''n''' carbon atoms share the empirical formula CnH2n+2 But for all '''n''' >= 4 there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when '''n''' increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. ;Example: With '''n''' = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with '''n''' = 4 there are two configurations: :::* a straight chain: (CH3)(CH2)(CH2)(CH3) :::* a branched chain: (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number '''n''' of carbon atoms of a molecule (for instance '''17'''). The output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17). The sequence of those results is visible in the OEIS entry: ::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... ;Extra credit: Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane H H H H H H H H H | | | | | | | | | H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H | | | | | | | | | H H H H H H H | H | H - C - H | H ;Links: * A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf * A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs * A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm * A Fortress implementation: (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
MAX_N = 500 BRANCH = 4 def tree(br, n, l=n, sum=1, cnt=1) for b in br+1 .. BRANCH sum += n return if sum >= MAX_N # prevent unneeded long math return if l * 2 >= sum and b >= BRANCH if b == br + 1 c = $ra[n] * cnt else c = c * ($ra[n] + (b - br - 1)) / (b - br) end $unrooted[sum] += c if l * 2 < sum next if b >= BRANCH $ra[sum] += c (1...n).each {|m| tree(b, m, l, sum, c)} end end def bicenter(s) return if s.odd? aux = $ra[s / 2] $unrooted[s] += aux * (aux + 1) / 2 end $ra = [0] * MAX_N $unrooted = [0] * MAX_N $ra[0] = $ra[1] = $unrooted[0] = $unrooted[1] = 1 for n in 1...MAX_N tree(0, n) bicenter(n) puts "%d: %d" % [n, $unrooted[n]] end
Parse an IP Address
Ruby
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: ::: {| border="5" cellspacing="0" cellpadding=2 |- |127.0.0.1 |The "localhost" IPv4 address |- |127.0.0.1:80 |The "localhost" IPv4 address, with a specified port (80) |- |::1 |The "localhost" IPv6 address |- |[::1]:80 |The "localhost" IPv6 address, with a specified port (80) |- |2605:2700:0:3::4713:93e3 |Rosetta Code's primary server's public IPv6 address |- |[2605:2700:0:3::4713:93e3]:80 |Rosetta Code's primary server's public IPv6 address, with a specified port (80) |} ;Task: Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. ;Example: '''127.0.0.1''' has the address number '''7F000001''' (2130706433 decimal) in the ipv4 address space. '''::ffff:127.0.0.1''' represents the same address in the ipv6 address space where it has the address number '''FFFF7F000001''' (281472812449793 decimal). '''::1''' has address number '''1''' and serves the same purpose in the ipv6 address space that '''127.0.0.1''' serves in the ipv4 address space.
require 'ipaddr' TESTCASES = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80"] output = [%w(String Address Port Family Hex), %w(------ ------- ---- ------ ---)] def output_table(rows) widths = [] rows.each {|row| row.each_with_index {|col, i| widths[i] = [widths[i].to_i, col.to_s.length].max }} format = widths.map {|size| "%#{size}s"}.join("\t") rows.each {|row| puts format % row} end TESTCASES.each do |str| case str # handle port; IPAddr does not. when /\A\[(?<address> .* )\]:(?<port> \d+ )\z/x # string like "[::1]:80" address, port = $~[:address], $~[:port] when /\A(?<address> [^:]+ ):(?<port> \d+ )\z/x # string like "127.0.0.1:80" address, port = $~[:address], $~[:port] else # string with no port number address, port = str, nil end ip_addr = IPAddr.new(address) family = "IPv4" if ip_addr.ipv4? family = "IPv6" if ip_addr.ipv6? output << [str, ip_addr.to_s, port.to_s, family, ip_addr.to_i.to_s(16)] end output_table(output)
Parsing/RPN calculator algorithm
Ruby
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''. * Assume an input of a correct, space separated, string of tokens of an RPN expression * Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: 3 4 2 * 1 5 - 2 3 ^ ^ / + * Print or display the output here ;Notes: * '''^''' means exponentiation in the expression above. * '''/''' means division. ;See also: * [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression. * Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task). * [[Parsing/RPN to infix conversion]]. * [[Arithmetic evaluation]].
rpn = RPNExpression("3 4 2 * 1 5 - 2 3 ^ ^ / +") value = rpn.eval
Parsing/Shunting-yard algorithm
Ruby
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. * Assume an input of a correct, space separated, string of tokens representing an infix expression * Generate a space separated output string representing the RPN * Test with the input string: :::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 * print and display the output here. * Operator precedence is given in this table: :{| class="wikitable" ! operator !! associativity !! operation |- || align="center" | ^ || 4 || right || exponentiation |- || align="center" | * || 3 || left || multiplication |- || align="center" | / || 3 || left || division |- || align="center" | + || 2 || left || addition |- || align="center" | - || 2 || left || subtraction |} ;Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. ;Note The handling of functions and arguments is not required. ;See also: * [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression. * [[Parsing/RPN to infix conversion]].
rpn = RPNExpression.from_infix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")
Pascal's triangle/Puzzle
Ruby
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). ;Task: Write a program to find a solution to this puzzle.
require 'rref' pyramid = [ [ 151], [nil,nil], [40,nil,nil], [nil,nil,nil,nil], ["x", 11,"y", 4,"z"] ] pyramid.each{|row| p row} equations = [[1,-1,1,0]] # y = x + z def parse_equation(str) eqn = [0] * 4 lhs, rhs = str.split("=") eqn[3] = rhs.to_i for term in lhs.split("+") case term when "x" then eqn[0] += 1 when "y" then eqn[1] += 1 when "z" then eqn[2] += 1 else eqn[3] -= term.to_i end end eqn end -2.downto(-5) do |row| pyramid[row].each_index do |col| val = pyramid[row][col] sum = "%s+%s" % [pyramid[row+1][col], pyramid[row+1][col+1]] if val.nil? pyramid[row][col] = sum else equations << parse_equation(sum + "=#{val}") end end end reduced = convert_to(reduced_row_echelon_form(equations), :to_i) for eqn in reduced if eqn[0] + eqn[1] + eqn[2] != 1 fail "no unique solution! #{equations.inspect} ==> #{reduced.inspect}" elsif eqn[0] == 1 then x = eqn[3] elsif eqn[1] == 1 then y = eqn[3] elsif eqn[2] == 1 then z = eqn[3] end end puts puts "x == #{x}" puts "y == #{y}" puts "z == #{z}" answer = [] for row in pyramid answer << row.collect {|cell| eval cell.to_s} end puts answer.each{|row| p row}
Pascal matrix generation
Ruby
A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr. Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. A Pascal upper-triangular matrix that is populated with jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] ;Task: Write functions capable of generating each of the three forms of n-by-n matrices. Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows). ;Note: The [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Upper, lower, and symetric Pascal Matrix - Nigel Galloway: May 3rd., 21015 require 'pp' ng = (g = 0..4).collect{[]} g.each{|i| g.each{|j| ng[i][j] = i==0 ? 1 : j<i ? 0 : ng[i-1][j-1]+ng[i][j-1]}} pp ng; puts g.each{|i| g.each{|j| ng[i][j] = j==0 ? 1 : i<j ? 0 : ng[i-1][j-1]+ng[i-1][j]}} pp ng; puts g.each{|i| g.each{|j| ng[i][j] = (i==0 or j==0) ? 1 : ng[i-1][j ]+ng[i][j-1]}} pp ng
Password generator
Ruby
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a --> z upper-case letters: A --> Z digits: 0 --> 9 other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include ''at least one'' (of each of the four groups): lower-case letter, upper-case letter, digit (numeral), and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example: Il1 O0 5S 2Z where the characters are: ::::* capital eye, lowercase ell, the digit one ::::* capital oh, the digit zero ::::* the digit five, capital ess ::::* the digit two, capital zee
ARRS = [("a".."z").to_a, ("A".."Z").to_a, ("0".."9").to_a, %q(!"#$%&'()*+,-./:;<=>?@[]^_{|}~).chars] # " quote to reset clumsy code colorizer ALL = ARRS.flatten def generate_pwd(size, num) raise ArgumentError, "Desired size too small" unless size >= ARRS.size num.times.map do arr = ARRS.map(&:sample) (size - ARRS.size).times{ arr << ALL.sample} arr.shuffle.join end end puts generate_pwd(8,3)
Pathological floating point problems
Ruby
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. '''A sequence that seems to converge to a wrong limit.''' Consider the sequence: :::::: v1 = 2 :::::: v2 = -4 :::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2) As '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''. ;Task 1: Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 ;Task 2: '''The Chaotic Bank Society''' is offering a new investment account to their customers. You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... ::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. ::* after 2 years your balance will be doubled and $1 removed. ::* after 3 years your balance will be tripled and $1 removed. ::* ... ::* after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after 25 years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 ;Task 3, extra credit: '''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988. :::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) :::::: compute f(a,b) where a=77617.0 and b=33096.0 :::::: f(77617.0, 33096.0) = -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. ;See also; * Floating-Point Arithmetic Section 1.3.2 Difficult problems.
ar = [0, 2, -4] 100.times{ar << (111 - 1130.quo(ar[-1])+ 3000.quo(ar[-1]*ar[-2])) } [3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n| puts "%3d -> %0.16f" % [n, ar[n]] end
Peaceful chess queen armies
Ruby from Java
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour. \ | / = = = = / | \ / | \ | The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''. ;Task: # Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). # Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. # Display here results for the m=4, n=5 case. ;References: * Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. * A250000 OEIS
class Position attr_reader :x, :y def initialize(x, y) @x = x @y = y end def ==(other) self.x == other.x && self.y == other.y end def to_s '(%d, %d)' % [@x, @y] end def to_str to_s end end def isAttacking(queen, pos) return queen.x == pos.x || queen.y == pos.y || (queen.x - pos.x).abs() == (queen.y - pos.y).abs() end def place(m, n, blackQueens, whiteQueens) if m == 0 then return true end placingBlack = true for i in 0 .. n-1 for j in 0 .. n-1 catch :inner do pos = Position.new(i, j) for queen in blackQueens if pos == queen || !placingBlack && isAttacking(queen, pos) then throw :inner end end for queen in whiteQueens if pos == queen || placingBlack && isAttacking(queen, pos) then throw :inner end end if placingBlack then blackQueens << pos placingBlack = false else whiteQueens << pos if place(m - 1, n, blackQueens, whiteQueens) then return true end blackQueens.pop whiteQueens.pop placingBlack = true end end end end if !placingBlack then blackQueens.pop end return false end def printBoard(n, blackQueens, whiteQueens) # initialize the board board = Array.new(n) { Array.new(n) { ' ' } } for i in 0 .. n-1 for j in 0 .. n-1 if i % 2 == j % 2 then board[i][j] = '•' else board[i][j] = '◦' end end end # insert the queens for queen in blackQueens board[queen.y][queen.x] = 'B' end for queen in whiteQueens board[queen.y][queen.x] = 'W' end # print the board for row in board for cell in row print cell, ' ' end print "\n" end print "\n" end nms = [ [2, 1], [3, 1], [3, 2], [4, 1], [4, 2], [4, 3], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [7, 1], [7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [7, 7] ] for nm in nms m = nm[1] n = nm[0] print "%d black and %d white queens on a %d x %d board:\n" % [m, m, n, n] blackQueens = [] whiteQueens = [] if place(m, n, blackQueens, whiteQueens) then printBoard(n, blackQueens, whiteQueens) else print "No solution exists.\n\n" end end
Perfect shuffle
Ruby
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: ::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: ::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right" |- | ''original:'' || 1 2 3 4 5 6 7 8 |- | ''after 1st shuffle:'' || 1 5 2 6 3 7 4 8 |- | ''after 2nd shuffle:'' || 1 3 5 7 2 4 6 8 |- | ''after 3rd shuffle:'' || 1 2 3 4 5 6 7 8 |} '''''The Task''''' # Write a function that can perform a perfect shuffle on an even-sized list of values. # Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. #* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. #* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. '''''Test Cases''''' ::::: {| class="wikitable" |- ! input ''(deck size)'' !! output ''(number of shuffles required)'' |- | 8 || 3 |- | 24 || 11 |- | 52 || 8 |- | 100 || 30 |- | 1020 || 1018 |- | 1024 || 10 |- | 10000 || 300 |}
def perfect_shuffle(deck_size = 52) deck = (1..deck_size).to_a original = deck.dup half = deck_size / 2 1.step do |i| deck = deck.first(half).zip(deck.last(half)).flatten return i if deck == original end end [8, 24, 52, 100, 1020, 1024, 10000].each {|i| puts "Perfect shuffles required for deck size #{i}: #{perfect_shuffle(i)}"}
Perfect totient numbers
Ruby
Generate and show here, the first twenty Perfect totient numbers. ;Related task: ::* [[Totient function]] ;Also see: ::* the OEIS entry for perfect totient numbers. ::* mrob list of the first 54
require "prime" class Integer def φ prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } end def perfect_totient? f, sum = self, 0 until f == 1 do f = f.φ sum += f end self == sum end end puts (1..).lazy.select(&:perfect_totient?).first(20).join(", ")
Permutations/Derangements
Ruby
A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. There are various ways to calculate !''n''. ;Task: # Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer). # Generate ''and show'' all the derangements of 4 integers using the above routine. # Create a function that calculates the subfactorial of ''n'', !''n''. # Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive. ;Optional stretch goal: * Calculate !''20'' ;Related tasks: * [[Anagrams/Deranged anagrams]] * [[Best shuffle]] * [[Left_factorials]]
def derangements(n) ary = (1 .. n).to_a ary.permutation.select do |perm| ary.zip(perm).all? {|a,b| a != b} end end def subfact(n) case n when 0 then 1 when 1 then 0 else (n-1)*(subfact(n-1) + subfact(n-2)) end end puts "derangements for n = 4" derangements(4).each{|d|p d} puts "\n n derange subfact" (0..9).each do |n| puts "%2d :%8d,%8d" % [n, derangements(n).size, subfact(n)] end puts "\nNumber of derangements" (10..20).each do |n| puts "#{n} : #{subfact(n)}" end
Permutations/Rank of a permutation
Ruby
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1). For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank: PERMUTATION RANK (0, 1, 2, 3) -> 0 (0, 1, 3, 2) -> 1 (0, 2, 1, 3) -> 2 (0, 2, 3, 1) -> 3 (0, 3, 1, 2) -> 4 (0, 3, 2, 1) -> 5 (1, 0, 2, 3) -> 6 (1, 0, 3, 2) -> 7 (1, 2, 0, 3) -> 8 (1, 2, 3, 0) -> 9 (1, 3, 0, 2) -> 10 (1, 3, 2, 0) -> 11 (2, 0, 1, 3) -> 12 (2, 0, 3, 1) -> 13 (2, 1, 0, 3) -> 14 (2, 1, 3, 0) -> 15 (2, 3, 0, 1) -> 16 (2, 3, 1, 0) -> 17 (3, 0, 1, 2) -> 18 (3, 0, 2, 1) -> 19 (3, 1, 0, 2) -> 20 (3, 1, 2, 0) -> 21 (3, 2, 0, 1) -> 22 (3, 2, 1, 0) -> 23 Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above). One use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them. A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items. ;Task: # Create a function to generate a permutation from a rank. # Create the inverse function that given the permutation generates its rank. # Show that for n=3 the two functions are indeed inverses of each other. # Compute and show here 4 random, individual, samples of permutations of 12 objects. ;Stretch goal: * State how reasonable it would be to use your program to address the limits of the Stack Overflow question. ;References: # Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here). # Ranks on the DevData site. # Another answer on Stack Overflow to a different question that explains its algorithm in detail. ;Related tasks: #[[Factorial_base_numbers_indexing_permutations_of_a_collection]]
class Permutation include Enumerable attr_reader :num_elements, :size def initialize(num_elements) @num_elements = num_elements @size = fact(num_elements) end def each return self.to_enum unless block_given? (0...@size).each{|i| yield unrank(i)} end def unrank(r) # nonrecursive version of Myrvold Ruskey unrank2 algorithm. pi = (0...num_elements).to_a (@num_elements-1).downto(1) do |n| s, r = r.divmod(fact(n)) pi[n], pi[s] = pi[s], pi[n] end pi end def rank(pi) # nonrecursive version of Myrvold Ruskey rank2 algorithm. pi = pi.dup pi1 = pi.zip(0...pi.size).sort.map(&:last) (pi.size-1).downto(0).inject(0) do |memo,i| pi[i], pi[pi1[i]] = pi[pi1[i]], (s = pi[i]) pi1[s], pi1[i] = pi1[i], pi1[s] memo += s * fact(i) end end private def fact(n) n.zero? ? 1 : n.downto(1).inject(:*) end end
Permutations by swapping
Ruby from BBC BASIC
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation ''here''. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement. ;References: * Steinhaus-Johnson-Trotter algorithm * Johnson-Trotter Algorithm Listing All Permutations * Heap's algorithm * Tintinnalogia ;Related tasks: * [[Matrix arithmetic] * [[Gray code]]
def perms(n) p = Array.new(n+1){|i| -i} s = 1 loop do yield p[1..-1].map(&:abs), s k = 0 for i in 2..n k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs end for i in 1...n k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs end break if k.zero? for i in 1..n p[i] *= -1 if p[i].abs > p[k].abs end i = k + (p[k] <=> 0) p[k], p[i] = p[i], p[k] s = -s end end for i in 3..4 perms(i){|perm, sign| puts "Perm: #{perm} Sign: #{sign}"} puts end
Phrase reversals
Ruby
Given a string of space separated words containing the following phrase: rosetta code phrase reversal :# Reverse the characters of the string. :# Reverse the characters of each individual word in the string, maintaining original word order within the string. :# Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here.
str = "rosetta code phrase reversal" puts str.reverse # Reversed string. puts str.split.map(&:reverse).join(" ") # Words reversed. puts str.split.reverse.join(" ") # Word order reversed.
Pig the dice game
Ruby
The game of Pig is a multiplayer game played with a single six-sided die. The object of the game is to reach '''100''' points or more. Play is taken in turns. On each person's turn that person has the option of either: :# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player. :# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player. ;Task: Create a program to score for, and simulate dice throws for, a two-person game. ;Related task: * [[Pig the dice game/Player]]
class PigGame Player = Struct.new(:name, :safescore, :score) do def bust!() self.score = safescore end def stay!() self.safescore = score end def to_s() "#{name} (#{safescore}, #{score})" end end def initialize(names, maxscore=100, die_sides=6) rotation = names.map {|name| Player.new(name,0,0) } rotation.cycle do |player| loop do if wants_to_roll?(player) puts "Rolled: #{roll=roll_dice(die_sides)}" if bust?(roll) puts "Busted!",'' player.bust! break else player.score += roll if player.score >= maxscore puts player.name + " wins!" return end end else player.stay! puts "Staying with #{player.safescore}!", '' break end end end end def roll_dice(die_sides) rand(1..die_sides) end def bust?(roll) roll==1 end def wants_to_roll?(player) print "#{player}: Roll? (Y) " ['Y','y',''].include?(gets.chomp) end end PigGame.new( %w|Samuel Elizabeth| )
Pig the dice game/Player
Ruby
Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy. * State here the play strategies involved. * Show play during a game here. As a stretch goal: * Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger. ;Game Rules: The game of Pig is a multiplayer game played with a single six-sided die. The object of the game is to reach 100 points or more. Play is taken in turns. On each person's turn that person has the option of either # '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player. # '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player. ;References * Pig (dice) * The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
def player1(sum,sm) for i in 1..100 puts "player1 rolled" a=gets.chomp().to_i if (a>1 && a<7) sum+=a if sum>=100 puts "player1 wins" break end else goto player2(sum,sm) end i+=1 end end def player2(sum,sm) for j in 1..100 puts "player2 rolled" b=gets.chomp().to_i if(b>1 && b<7) sm+=b if sm>=100 puts "player2 wins" break end else player1(sum,sm) end j+=1 end end i=0 j=0 sum=0 sm=0 player1(sum,sm) return
Playfair cipher
Ruby
Implement a Playfair cipher for encryption and decryption. The user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet. The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces. ;Output example: HI DE TH EG OL DI NT HE TR EX ES TU MP
class Playfair Size = 5 def initialize(key, missing) @missing = missing.upcase alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split'' extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet grid = extended.uniq[0...Size*Size].each_slice(Size).to_a coords = {} grid.each_with_index do |row, i| row.each_with_index do |letter, j| coords[letter] = [i,j] end end @encode = {} alphabet.product(alphabet).reject { |a,b| a==b }.each do |a, b| i1, j1 = coords[a] i2, j2 = coords[b] if i1 == i2 then j1 = (j1 + 1) % Size j2 = (j2 + 1) % Size elsif j1 == j2 then i1 = (i1 + 1) % Size i2 = (i2 + 1) % Size else j1, j2 = j2, j1 end @encode["#{a}#{b}"] = "#{grid[i1][j1]}#{grid[i2][j2]}" @decode = @encode.invert end end def encode(plaintext) plain = plaintext.upcase.gsub(/[^A-Z]/,'') if @missing == 'J' then plain = plain.gsub(/J/, 'I') else plain = plain.gsub(@missing, 'X') end plain = plain.gsub(/(.)\1/, '\1X\1') if plain.length % 2 == 1 then plain += 'X' end return plain.upcase.split('').each_slice(2).map do |pair| @encode[pair.join] end.join.split('').each_slice(5).map{|s|s.join}.join(' ') end def decode(ciphertext) cipher = ciphertext.upcase.gsub(/[^A-Z]/,'') return cipher.upcase.split('').each_slice(2).map do |pair| @decode[pair.join] end.join.split('').each_slice(5).map{|s|s.join}.join(' ') end end
Poker hand analyser
Ruby
Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. ;Example: ::::'''2d''' (two of diamonds). Faces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k''' Suits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or alternatively, the unicode card-suit characters: Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid ;Examples: 2 2 2 k q: three-of-a-kind 2 5 7 8 9: high-card a 2 3 4 5: straight 2 3 2 3 3: full-house 2 7 2 3 3: two-pair 2 7 7 7 7: four-of-a-kind 10 j q k a: straight-flush 4 4 k 5 10: one-pair q 10 7 6 q: invalid The programs output for the above examples should be displayed here on this page. ;Extra credit: # use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). # allow two jokers ::* use the symbol '''joker''' ::* duplicates would be allowed (for jokers only) ::* five-of-a-kind would then be the highest hand ;More extra credit examples: joker 2 2 k q: three-of-a-kind joker 5 7 8 9: straight joker 2 3 4 5: straight joker 3 2 3 3: four-of-a-kind joker 7 2 3 3: three-of-a-kind joker 7 7 7 7: five-of-a-kind joker j q k A: straight-flush joker 4 k 5 10: one-pair joker k 7 6 4: flush joker 2 joker 4 5: straight joker Q joker A 10: straight joker Q joker A 10: straight-flush joker 2 2 joker q: four-of-a-kind ;Related tasks: * [[Playing cards]] * [[Card shuffles]] * [[Deal cards_for_FreeCell]] * [[War Card_Game]] * [[Go Fish]]
class Card include Comparable attr_accessor :ordinal attr_reader :suit, :face SUITS = %i(♥ ♦ ♣ ♠) FACES = %i(2 3 4 5 6 7 8 9 10 j q k a) def initialize(str) @face, @suit = parse(str) @ordinal = FACES.index(@face) end def <=> (other) #used for sorting self.ordinal <=> other.ordinal end def to_s "#@face#@suit" end private def parse(str) face, suit = str.chop.to_sym, str[-1].to_sym raise ArgumentError, "invalid card: #{str}" unless FACES.include?(face) && SUITS.include?(suit) [face, suit] end end class Hand include Comparable attr_reader :cards, :rank RANKS = %i(high-card one-pair two-pair three-of-a-kind straight flush full-house four-of-a-kind straight-flush five-of-a-kind) WHEEL_FACES = %i(2 3 4 5 a) def initialize(str_of_cards) @cards = str_of_cards.downcase.tr(',',' ').split.map{|str| Card.new(str)} grouped = @cards.group_by(&:face).values @face_pattern = grouped.map(&:size).sort @rank = categorize @rank_num = RANKS.index(@rank) @tiebreaker = grouped.map{|ar| [ar.size, ar.first.ordinal]}.sort.reverse end def <=> (other) # used for sorting and comparing self.compare_value <=> other.compare_value end def to_s @cards.map(&:to_s).join(" ") end protected # accessible for Hands def compare_value [@rank_num, @tiebreaker] end private def one_suit? @cards.map(&:suit).uniq.size == 1 end def consecutive? sort.each_cons(2).all? {|c1,c2| c2.ordinal - c1.ordinal == 1 } end def sort if @cards.sort.map(&:face) == WHEEL_FACES @cards.detect {|c| c.face == :a}.ordinal = -1 end @cards.sort end def categorize if consecutive? one_suit? ? :'straight-flush' : :straight elsif one_suit? :flush else case @face_pattern when [1,1,1,1,1] then :'high-card' when [1,1,1,2] then :'one-pair' when [1,2,2] then :'two-pair' when [1,1,3] then :'three-of-a-kind' when [2,3] then :'full-house' when [1,4] then :'four-of-a-kind' when [5] then :'five-of-a-kind' end end end end # Demo test_hands = <<EOS 2♥ 2♦ 2♣ k♣ q♦ 2♥ 5♥ 7♦ 8♣ 9♠ a♥ 2♦ 3♣ 4♣ 5♦ 2♥ 3♥ 2♦ 3♣ 3♦ 2♥ 7♥ 2♦ 3♣ 3♦ 2♥ 6♥ 2♦ 3♣ 3♦ 10♥ j♥ q♥ k♥ a♥ 4♥ 4♠ k♠ 2♦ 10♠ 4♥ 4♠ k♠ 3♦ 10♠ q♣ 10♣ 7♣ 6♣ 4♣ q♣ 10♣ 7♣ 6♣ 3♣ 9♥ 10♥ q♥ k♥ j♣ 2♥ 3♥ 4♥ 5♥ a♥ 2♥ 2♥ 2♦ 3♣ 3♦ EOS hands = test_hands.each_line.map{|line| Hand.new(line) } puts "High to low" hands.sort.reverse.each{|hand| puts "#{hand}\t #{hand.rank}" } puts str = <<EOS joker 2♦ 2♠ k♠ q♦ joker 5♥ 7♦ 8♠ 9♦ joker 2♦ 3♠ 4♠ 5♠ joker 3♥ 2♦ 3♠ 3♦ joker 7♥ 2♦ 3♠ 3♦ joker 7♥ 7♦ 7♠ 7♣ joker j♥ q♥ k♥ A♥ joker 4♣ k♣ 5♦ 10♠ joker k♣ 7♣ 6♣ 4♣ joker 2♦ joker 4♠ 5♠ joker Q♦ joker A♠ 10♠ joker Q♦ joker A♦ 10♦ joker 2♦ 2♠ joker q♦ EOS # Neither the Card nor the Hand class supports jokers # but since hands are comparable, they are also sortable. # Try every card from a deck for a joker and pick the largest hand: DECK = Card::FACES.product(Card::SUITS).map(&:join) str.each_line do |line| cards_in_arrays = line.split.map{|c| c == "joker" ? DECK.dup : [c]} #joker is array of all cards all_tries = cards_in_arrays.shift.product(*cards_in_arrays).map{|ar| Hand.new(ar.join" ")} #calculate the Whatshisname product best = all_tries.max puts "#{line.strip}: #{best.rank}" end
Population count
Ruby
The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer. ''Population count'' is also known as: ::::* ''pop count'' ::::* ''popcount'' ::::* ''sideways sum'' ::::* ''bit summation'' ::::* ''Hamming weight'' For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''. ''Evil numbers'' are non-negative integers that have an ''even'' population count. ''Odious numbers'' are positive integers that have an ''odd'' population count. ;Task: * write a function (or routine) to return the population count of a non-negative integer. * all computation of the lists below should start with '''0''' (zero indexed). :* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329'''). :* display the 1st thirty ''evil'' numbers. :* display the 1st thirty ''odious'' numbers. * display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified. ;See also * The On-Line Encyclopedia of Integer Sequences: A000120 population count. * The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers. * The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
class Integer def popcount digits(2).count(1) #pre Ruby 2.4: self.to_s(2).count("1") end def evil? self >= 0 && popcount.even? end end puts "Powers of 3:", (0...30).map{|n| (3**n).popcount}.join(' ') puts "Evil:" , 0.step.lazy.select(&:evil?).first(30).join(' ') puts "Odious:", 0.step.lazy.reject(&:evil?).first(30).join(' ')
Priority queue
Ruby
A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. ;Task: Create a priority queue. The queue must support at least two operations: :# Insertion. An element is added to the queue with a priority (a numeric value). :# Top item removal. Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: '''Priority''' '''Task''' ---------- ---------------- 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
class PriorityQueueNaive def initialize(data=nil) @q = Hash.new {|h, k| h[k] = []} data.each {|priority, item| @q[priority] << item} if data @priorities = @q.keys.sort end def push(priority, item) @q[priority] << item @priorities = @q.keys.sort end def pop p = @priorities[0] item = @q[p].shift if @q[p].empty? @q.delete(p) @priorities.shift end item end def peek unless empty? @q[@priorities[0]][0] end end def empty? @priorities.empty? end def each @q.each do |priority, items| items.each {|item| yield priority, item} end end def dup @q.each_with_object(self.class.new) do |(priority, items), obj| items.each {|item| obj.push(priority, item)} end end def merge(other) raise TypeError unless self.class == other.class pq = dup other.each {|priority, item| pq.push(priority, item)} pq # return a new object end def inspect @q.inspect end end test = [ [6, "drink tea"], [3, "Clear drains"], [4, "Feed cat"], [5, "Make tea"], [6, "eat biscuit"], [1, "Solve RC tasks"], [2, "Tax return"], ] pq = PriorityQueueNaive.new test.each {|pr, str| pq.push(pr, str) } until pq.empty? puts pq.pop end puts test2 = test.shift(3) p pq1 = PriorityQueueNaive.new(test) p pq2 = PriorityQueueNaive.new(test2) p pq3 = pq1.merge(pq2) puts "peek : #{pq3.peek}" until pq3.empty? puts pq3.pop end puts "peek : #{pq3.peek}"
Pseudo-random numbers/Combined recursive generator MRG32k3a
Ruby from C
MRG32k3a Combined recursive generator (pseudo-code): /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of gen #1 */ x2 = [0, 0, 0] /* list of three last values of gen #2 */ method seed(u64 seed_state) assert seed_state in range >0 and < d x1 = [seed_state, 0, 0] x2 = [seed_state, 0, 0] end method method next_int() x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1 x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2 x1 = [x1i, x1[0], x1[1]] /* Keep last three */ x2 = [x2i, x2[0], x2[1]] /* Keep last three */ z = (x1i - x2i) % m1 answer = (z + 1) return answer end method method next_float(): return float next_int() / d end method end class :MRG32k3a Use: random_gen = instance MRG32k3a random_gen.seed(1234567) print(random_gen.next_int()) /* 1459213977 */ print(random_gen.next_int()) /* 2827710106 */ print(random_gen.next_int()) /* 4245671317 */ print(random_gen.next_int()) /* 3877608661 */ print(random_gen.next_int()) /* 2595287583 */ ;Task * Generate a class/set of functions that generates pseudo-random numbers as shown above. * Show that the first five integers generated with the seed `1234567` are as shown above * Show that for an initial seed of '987654321' the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931 * Show your output here, on this page.
def mod(x, y) m = x % y if m < 0 then if y < 0 then return m - y else return m + y end end return m end # Constants # First generator A1 = [0, 1403580, -810728] A1.freeze M1 = (1 << 32) - 209 # Second generator A2 = [527612, 0, -1370589] A2.freeze M2 = (1 << 32) - 22853 D = M1 + 1 # the last three values of the first generator $x1 = [0, 0, 0] # the last three values of the second generator $x2 = [0, 0, 0] def seed(seed_state) $x1 = [seed_state, 0, 0] $x2 = [seed_state, 0, 0] end def next_int() x1i = mod((A1[0] * $x1[0] + A1[1] * $x1[1] + A1[2] * $x1[2]), M1) x2i = mod((A2[0] * $x2[0] + A2[1] * $x2[1] + A2[2] * $x2[2]), M2) z = mod(x1i - x2i, M1) $x1 = [x1i, $x1[0], $x1[1]] $x2 = [x2i, $x2[0], $x2[1]] return z + 1 end def next_float() return 1.0 * next_int() / D end ######################################## seed(1234567) print next_int(), "\n" print next_int(), "\n" print next_int(), "\n" print next_int(), "\n" print next_int(), "\n" print "\n" counts = [0, 0, 0, 0, 0] seed(987654321) for i in 1 .. 100000 value = (next_float() * 5.0).floor counts[value] = counts[value] + 1 end counts.each_with_index { |v,i| print i, ": ", v, "\n" }
Pseudo-random numbers/Middle-square method
Ruby
{{Wikipedia|Middle-square method|en}} ; The Method: To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. ; Pseudo code: var seed = 675248 function random() var s = str(seed * seed) 'str: turn a number into string do while not len(s) = 12 s = "0" + s 'add zeroes before the string end do seed = val(mid(s, 4, 6)) 'mid: string variable, start, length 'val: turn a string into number return seed end function ; Middle-square method use: for i = 1 to 5 print random() end for ;Task: * Generate a class/set of functions that generates pseudo-random numbers (6 digits) as shown above. * Show the first five integers generated with the seed 675248 as shown above. * Show your output here, on this page.
def middle_square (seed) return to_enum(__method__, seed) unless block_given? s = seed.digits.size loop { yield seed = (seed*seed).to_s.rjust(s*2, "0")[s/2, s].to_i } end puts middle_square(675248).take(5)
Pseudo-random numbers/PCG32
Ruby from Python
Some definitions to help in the explanation: :Floor operation ::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions ::Greatest integer less than or equal to a real number. :Bitwise Logical shift operators (c-inspired) ::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts ::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. ::Examples are shown for 8 bit binary numbers; most significant bit to the left. :: '''<<''' Logical shift left by given number of bits. :::E.g Binary 00110101 '''<<''' 2 == Binary 11010100 :: '''>>''' Logical shift right by given number of bits. :::E.g Binary 00110101 '''>>''' 2 == Binary 00001101 :'''^''' Bitwise exclusive-or operator ::https://en.wikipedia.org/wiki/Exclusive_or ::Bitwise comparison for if bits differ :::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110 :'''|''' Bitwise or operator ::https://en.wikipedia.org/wiki/Bitwise_operation#OR ::Bitwise comparison gives 1 if any of corresponding bits are 1 :::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111 ;PCG32 Generator (pseudo-code): PCG32 has two unsigned 64-bit integers of internal state: # '''state''': All 2**64 values may be attained. # '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 ''different'' sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. ;Task: * Generate a class/set of functions that generates pseudo-random numbers using the above. * Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 * Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) :Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 * Show your output here, on this page.
class PCG32 MASK64 = (1 << 64) - 1 MASK32 = (1 << 32) - 1 CONST = 6364136223846793005 def seed(seed_state, seed_sequence) @state = 0 @inc = ((seed_sequence << 1) | 1) & MASK64 next_int @state = @state + seed_state next_int end def next_int old = @state @state = ((old * CONST) + @inc) & MASK64 xorshifted = (((old >> 18) ^ old) >> 27) & MASK32 rot = (old >> 59) & MASK32 answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)) answer & MASK32 end def next_float next_int.fdiv(1 << 32) end end random_gen = PCG32.new random_gen.seed(42, 54) 5.times{puts random_gen.next_int} random_gen.seed(987654321, 1) p 100_000.times.each{(random_gen.next_float * 5).floor}.tally.sort.to_h
Pseudo-random numbers/Xorshift star
Ruby
Some definitions to help in the explanation: :Floor operation ::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions ::Greatest integer less than or equal to a real number. :Bitwise Logical shift operators (c-inspired) ::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts ::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. ::Examples are shown for 8 bit binary numbers; most significant bit to the left. :: '''<<''' Logical shift left by given number of bits. :::E.g Binary 00110101 '''<<''' 2 == Binary 11010100 :: '''>>''' Logical shift right by given number of bits. :::E.g Binary 00110101 '''>>''' 2 == Binary 00001101 :'''^''' Bitwise exclusive-or operator ::https://en.wikipedia.org/wiki/Exclusive_or ::Bitwise comparison for if bits differ :::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110 ;Xorshift_star Generator (pseudo-code): /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class :;Xorshift use: random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ ;Task: * Generate a class/set of functions that generates pseudo-random numbers as shown above. * Show that the first five integers genrated with the seed 1234567 are as shown above * Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) :Is as follows: 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 * Show your output here, on this page.
class Xorshift_star MASK64 = (1 << 64) - 1 MASK32 = (1 << 32) - 1 def initialize(seed = 0) = @state = seed & MASK64 def next_int x = @state x = x ^ (x >> 12) x = (x ^ (x << 25)) & MASK64 x = x ^ (x >> 27) @state = x (((x * 0x2545F4914F6CDD1D) & MASK64) >> 32) & MASK32 end def next_float = next_int.fdiv((1 << 32)) end random_gen = Xorshift_star.new(1234567) 5.times{ puts random_gen.next_int} random_gen = Xorshift_star.new(987654321) tally = Hash.new(0) 100_000.times{ tally[(random_gen.next_float*5).floor] += 1 } puts tally.sort.map{|ar| ar.join(": ") }
Pythagorean quadruples
Ruby from VBA
One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): :::::::: a2 + b2 + c2 = d2 An example: :::::::: 22 + 32 + 62 = 72 ::::: which is: :::::::: 4 + 9 + 36 = 49 ;Task: For positive integers up '''2,200''' (inclusive), for all values of '''a''', '''b''', '''c''', and '''d''', find (and show here) those values of '''d''' that ''can't'' be represented. Show the values of '''d''' on one line of output (optionally with a title). ;Related tasks: * [[Euler's sum of powers conjecture]]. * [[Pythagorean triples]]. ;Reference: :* the Wikipedia article: Pythagorean quadruple.
n = 2200 l_add, l = {}, {} 1.step(n) do |x| x2 = x*x x.step(n) {|y| l_add[x2 + y*y] = true} end s = 3 1.step(n) do |x| s1 = s s += 2 s2 = s (x+1).step(n) do |y| l[y] = true if l_add[s1] s1 += s2 s2 += 2 end end puts (1..n).reject{|x| l[x]}.join(" ")
Pythagorean triples
Ruby from Java
A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2. They are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\rm gcd}(a, b) = {\rm gcd}(a, c) = {\rm gcd}(b, c) = 1. Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\rm gcd}(a, b) = 1). Each triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c. ;Task: The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. ;Extra credit: Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner. ;Related tasks: * [[Euler's sum of powers conjecture]] * [[List comprehensions]] * [[Pythagorean quadruples]]
class PythagoranTriplesCounter def initialize(limit) @limit = limit @total = 0 @primitives = 0 generate_triples(3, 4, 5) end attr_reader :total, :primitives private def generate_triples(a, b, c) perim = a + b + c return if perim > @limit @primitives += 1 @total += @limit / perim generate_triples( a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c) generate_triples( a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c) generate_triples(-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c) end end perim = 10 while perim <= 100_000_000 c = PythagoranTriplesCounter.new perim p [perim, c.total, c.primitives] perim *= 10 end
Quaternion type
Ruby 1.9
complex numbers. A complex number has a real and complex part, sometimes written as a + bi, where a and b stand for real numbers, and i stands for the square root of minus 1. An example of a complex number might be -3 + 2i, where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. A quaternion has one real part and ''three'' imaginary parts, i, j, and k. A quaternion might be written as a + bi + cj + dk. In the quaternion numbering system: :::* ii = jj = kk = ijk = -1, or more simply, :::* ii = jj = kk = ijk = -1. The order of multiplication is important, as, in general, for two quaternions: :::: q1 and q2: q1q2 q2q1. An example of a quaternion might be 1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. So the example above would be written as (1, 2, 3, 4) ;Task: Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number r = 7. Create functions (or classes) to perform simple maths with quaternions including computing: # The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2} # The negative of a quaternion: = (-a, -b, -c, -d) # The conjugate of a quaternion: = ( a, -b, -c, -d) # Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) # Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) # Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) # Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) # Show that, for the two quaternions q1 and q2: q1q2 q2q1 If a language has built-in support for quaternions, then use it. ;C.f.: * [[Vector products]] * On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
class Quaternion def initialize(*parts) raise ArgumentError, "wrong number of arguments (#{parts.size} for 4)" unless parts.size == 4 raise ArgumentError, "invalid value of quaternion parts #{parts}" unless parts.all? {|x| x.is_a?(Numeric)} @parts = parts end def to_a; @parts; end def to_s; "Quaternion#{@parts.to_s}" end alias inspect to_s def complex_parts; [Complex(*to_a[0..1]), Complex(*to_a[2..3])]; end def real; @parts.first; end def imag; @parts[1..3]; end def conj; Quaternion.new(real, *imag.map(&:-@)); end def norm; Math.sqrt(to_a.reduce(0){|sum,e| sum + e**2}) end # In Rails: Math.sqrt(to_a.sum { e**2 }) def ==(other) case other when Quaternion; to_a == other.to_a when Numeric; to_a == [other, 0, 0, 0] else false end end def -@; Quaternion.new(*to_a.map(&:-@)); end def -(other); self + -other; end def +(other) case other when Numeric Quaternion.new(real + other, *imag) when Quaternion Quaternion.new(*to_a.zip(other.to_a).map { |x,y| x + y }) # In Rails: zip(other).map(&:sum) end end def *(other) case other when Numeric Quaternion.new(*to_a.map { |x| x * other }) when Quaternion # Multiplication of quaternions in C x C space. See "Cayley-Dickson construction". a, b, c, d = *complex_parts, *other.complex_parts x, y = a*c - d.conj*b, a*d + b*c.conj Quaternion.new(x.real, x.imag, y.real, y.imag) end end # Coerce is called by Ruby to return a compatible type/receiver when the called method/operation does not accept a Quaternion def coerce(other) case other when Numeric then [Scalar.new(other), self] else raise TypeError, "#{other.class} can't be coerced into #{self.class}" end end class Scalar def initialize(val); @val = val; end def +(other); other + @val; end def *(other); other * @val; end def -(other); Quaternion.new(@val, 0, 0, 0) - other; end end end if __FILE__ == $0 q = Quaternion.new(1,2,3,4) q1 = Quaternion.new(2,3,4,5) q2 = Quaternion.new(3,4,5,6) r = 7 expressions = ["q", "q1", "q2", "q.norm", "-q", "q.conj", "q + r", "r + q","q1 + q2", "q2 + q1", "q * r", "r * q", "q1 * q2", "q2 * q1", "(q1 * q2 != q2 * q1)", "q - r", "r - q"] expressions.each do |exp| puts "%20s = %s" % [exp, eval(exp)] end end
RIPEMD-160
Ruby
'''RIPEMD-160''' is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like [[MD4]] (RFC 1320). Find the RIPEMD-160 message digest of a string of [[octet]]s. Use the ASCII encoded string "Rosetta Code". You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
require 'stringio' module RMD160 # functions and constants MASK = (1 << 32) - 1 F = [ proc {|x, y, z| x ^ y ^ z}, proc {|x, y, z| (x & y) | (x.^(MASK) & z)}, proc {|x, y, z| (x | y.^(MASK)) ^ z}, proc {|x, y, z| (x & z) | (y & z.^(MASK))}, proc {|x, y, z| x ^ (y | z.^(MASK))}, ].freeze K = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] KK = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] R = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13] RR = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11] S = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6] SS = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11] module_function def rol(value, shift) (value << shift).&(MASK) | (value.&(MASK) >> (32 - shift)) end # Calculates RIPEMD-160 message digest of _string_. Returns binary # digest. For hexadecimal digest, use # +*RMD160.rmd160(string).unpack('H*')+. def rmd160(string) # initial hash h0 = 0x67452301 h1 = 0xefcdab89 h2 = 0x98badcfe h3 = 0x10325476 h4 = 0xc3d2e1f0 io = StringIO.new(string) block = "" term = false # appended "\x80" in second-last block? last = false # last block? until last # Read next block of 16 words (64 bytes, 512 bits). io.read(64, block) or ( # Work around a bug in Rubinius 1.2.4. At eof, # MRI and JRuby already replace block with "". block.replace("") ) # Unpack block into 32-bit words "V". case len = block.length when 64 # Unpack 16 words. x = block.unpack("V16") when 56..63 # Second-last block: append padding, unpack 16 words. block.concat("\x80"); term = true block.concat("\0" * (63 - len)) x = block.unpack("V16") when 0..55 # Last block: append padding, unpack 14 words. block.concat(term ? "\0" : "\x80") block.concat("\0" * (55 - len)) x = block.unpack("V14") # Append bit length, 2 words. bit_len = string.length << 3 x.push(bit_len & MASK, bit_len >> 32) last = true else fail "impossible" end # Process this block. a, b, c, d, e = h0, h1, h2, h3, h4 aa, bb, cc, dd, ee = h0, h1, h2, h3, h4 j = 0 5.times {|ro| f, ff = F[ro], F[4 - ro] k, kk = K[ro], KK[ro] 16.times { a, e, d, c, b = e, d, rol(c, 10), b, rol(a + f[b, c, d] + x[R[j]] + k, S[j]) + e aa, ee, dd, cc, bb = ee, dd, rol(cc, 10), bb, rol(aa + ff[bb, cc, dd] + x[RR[j]] + kk, SS[j]) + ee j += 1 } } h0, h1, h2, h3, h4 = (h1 + c + dd) & MASK, (h2 + d + ee) & MASK, (h3 + e + aa) & MASK, (h4 + a + bb) & MASK, (h0 + b + cc) & MASK end # until last [h0, h1, h2, h3, h4].pack("V5") end end if __FILE__ == $0 # Print an example RIPEMD-160 digest. str = 'Rosetta Code' printf "%s:\n %s\n", str, *RMD160.rmd160(str).unpack('H*') end
RPG attributes generator
Ruby
'''RPG''' = Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: * The total of all character attributes must be at least 75. * At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. ;Task: Write a program that: # Generates 4 random, whole values between 1 and 6. # Saves the sum of the 3 largest values. # Generates a total of 6 values this way. # Displays the total, and all 6 values once finished. * The order in which each value was generated must be preserved. * The total of all 6 values must be at least 75. * At least 2 of the values must be 15 or more.
res = [] until res.sum >= 75 && res.count{|n| n >= 15} >= 2 do res = Array.new(6) do a = Array.new(4){rand(1..6)} a.sum - a.min end end p res puts "sum: #{res.sum}"
Ramanujan's constant
Ruby
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the e**(p*''x'') approach, show that when evaluated with the last four Heegner numbers the result is ''almost'' an integer.
require "bigdecimal/math" include BigMath e, pi = E(200), PI(200) [19, 43, 67, 163].each do |x| puts "#{x}: #{(e ** (pi * BigMath.sqrt(BigDecimal(x), 200))).round(100).to_s("F")}" end
Random Latin squares
Ruby
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. For the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero. ;Example n=4 randomised Latin square: 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 ;Task: # Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. # Use the function to generate ''and show here'', two randomly generated squares of size 5. ;Note: Strict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task. ;Related tasks: * [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]] * [[Latin Squares in reduced form]] ;Reference: * Wikipedia: Latin square * OEIS: A002860
N = 5 def generate_square perms = (1..N).to_a.permutation(N).to_a.shuffle square = [] N.times do square << perms.pop perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} } end square end def print_square(square) cell_size = N.digits.size + 1 strings = square.map!{|row| row.map!{|el| el.to_s.rjust(cell_size)}.join } puts strings, "\n" end 2.times{print_square( generate_square)}
Random number generator (device)
Ruby
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then: show how to obtain a random 32-bit number from that mechanism. ;Related task * [[Random_number_generator_(included)]]
require 'securerandom' SecureRandom.random_number(1 << 32) #or specifying SecureRandom as the desired RNG: p (1..10).to_a.sample(3, random: SecureRandom) # =>[1, 4, 5]
Random number generator (included)
Ruby
The task is to: : State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. : If possible, give a link to a wider explanation of the algorithm used. Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
Ruby's <code>rand</code> function currently uses the [[wp:Mersenne twister|Mersenne twister]] algorithm, as described in [http://www.ruby-doc.org/core/classes/Kernel.html#M005974 its documentation].
Range expansion
Ruby
{{:Range extraction/Format}} ;Task: Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the '''range from minus 3 to ''minus'' 1'''. ;Related task: * [[Range extraction]]
def range_expand(rng) rng.split(',').flat_map do |part| if part =~ /^(-?\d+)-(-?\d+)$/ ($1.to_i .. $2.to_i).to_a else Integer(part) end end end p range_expand('-6,-3--1,3-5,7-11,14,15,17-20')
Range extraction
Ruby
{{:Range extraction/Format}} ;Task: * Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. * Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 * Show the output of your program. ;Related task: * [[Range expansion]]
def range_extract(l) # pad the list with a big value, so that the last loop iteration will # append something to the range sorted, range = l.sort.concat([Float::MAX]), [] canidate_number = sorted.first # enumerate over the sorted list in pairs of current number and next by index sorted.each_cons(2) do |current_number, next_number| # if there is a gap between the current element and its next by index if current_number.succ < next_number # if current element is our first or our next by index if canidate_number == current_number # put the first element or next by index into our range as a string range << canidate_number.to_s else # if current element is not the same as the first or next # add [first or next, first or next equals current add , else -, current] seperator = canidate_number.succ == current_number ? "," : "-" range << "%d%s%d" % [canidate_number, seperator, current_number] end # make the first element the next element canidate_number = next_number end end range.join(',') end lst = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 ] p rng = range_extract(lst)
Range extraction
Ruby 2.2
{{:Range extraction/Format}} ;Task: * Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. * Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 * Show the output of your program. ;Related task: * [[Range expansion]]
ary = [0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39] puts ary.sort.slice_when{|i,j| i+1 != j}.map{|a| a.size<3 ? a : "#{a[0]}-#{a[-1]}"}.join(",")
Rate counter
Ruby
Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed. Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: * Run N seconds worth of jobs and/or Y jobs. * Report at least three distinct times. Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can. '''See also:''' [[System time]], [[Time a function]]
require 'benchmark' Document = Struct.new(:id,:a,:b,:c) documents_a = [] documents_h = {} 1.upto(10_000) do |n| d = Document.new(n) documents_a << d documents_h[d.id] = d end searchlist = Array.new(1000){ rand(10_000)+1 } Benchmark.bm(10) do |x| x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} } x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} } end
Recaman's sequence
Ruby from Kotlin
The '''Recaman's sequence''' generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated. If the conditions ''don't'' hold then a(n) = a(n-1) + n. ;Task: # Generate and show here the first 15 members of the sequence. # Find and show here, the first duplicated number in the sequence. # '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. ;References: * A005132, The On-Line Encyclopedia of Integer Sequences. * The Slightly Spooky Recaman Sequence, Numberphile video. * Recaman's sequence, on Wikipedia.
require 'set' a = [0] used = Set[0] used1000 = Set[0] foundDup = false n = 1 while n <= 15 or not foundDup or used1000.size < 1001 nxt = a[n - 1] - n if nxt < 1 or used === nxt then nxt = nxt + 2 * n end alreadyUsed = used === nxt a << nxt if not alreadyUsed then used << nxt if nxt >= 0 and nxt <= 1000 then used1000 << nxt end end if n == 14 then print "The first 15 terms of the Recaman's sequence are ", a, "\n" end if not foundDup and alreadyUsed then print "The first duplicated term is a[", n, "] = ", nxt, "\n" foundDup = true end if used1000.size == 1001 then print "Terms up to a[", n, "] are needed to generate 0 to 1000\n" end n = n + 1 end
Remove lines from a file
Ruby
Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
require 'tempfile' def remove_lines(filename, start, num) tmp = Tempfile.open(filename) do |fp| File.foreach(filename) do |line| if $. >= start and num > 0 num -= 1 else fp.puts line end end fp end puts "Warning: End of file encountered before all lines removed" if num > 0 FileUtils.copy(tmp.path, filename) tmp.unlink end # Test code def setup(filename, start, remove) puts "remove #{remove} lines starting at line #{start}" File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}} puts "before:", File.read(filename) end def teardown(filename) puts "after:", File.read(filename) puts File.unlink(filename) end filename = "foobar.txt" start = 2 [2, 6].each do |remove| setup(filename, start, remove) remove_lines(filename, start, remove) teardown(filename) end
Rep-string
Ruby
Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''. For example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string. ;Task: * Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). * There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. * Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 * Show your output on this page.
ar = %w(1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1) ar.each do |str| rep_pos = (str.size/2).downto(1).find{|pos| str.start_with? str[pos..-1]} puts str, rep_pos ? " "*rep_pos + str[0, rep_pos] : "(no repetition)", "" end
Repeat
Ruby
Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
4.times{ puts "Example" } # idiomatic way def repeat(proc,num) num.times{ proc.call } end repeat(->{ puts "Example" }, 4)
Repunit primes
Ruby
portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, '''1'''. So 1, 11, 111, 1111 & 11111 are all repunits. Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime. In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.) In base three: 111, 1111111, 1111111111111, etc. ''Repunit primes, by definition, are also [[circular primes]].'' Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits ''might'' be prime. Rather than expanding the repunit out as a giant list of '''1'''s or converting to base 10, it is common to just list the ''number'' of '''1'''s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc. Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences. Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already. ;Task * For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000. ;Stretch * Increase the limit to 2700 (or as high as you have patience for.) ;See also ;* Wikipedia: Repunit primes ;* OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2) ;* OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3) ;* OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5) ;* OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6) ;* OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7) ;* OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10) ;* OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11) ;* OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12) ;* OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13) ;* OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14) ;* OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15) ;* Related task: Circular primes
require 'prime' require 'gmp' (2..16).each do |base| res = Prime.each(1000).select {|n| GMP::Z(("1" * n).to_i(base)).probab_prime? > 0} puts "Base #{base}: #{res.join(" ")}" end
Reverse words in a string
Ruby
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified. ;Example: Hey you, Bub! would be shown reversed as: Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string (or one just containing spaces) would be the result. '''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) ;Input data (ten lines within the box) line +----------------------------------------+ 1 | ---------- Ice and Fire ------------ | 2 | | <--- a blank line here. 3 | fire, in end will world the say Some | 4 | ice. in say Some | 5 | desire of tasted I've what From | 6 | fire. favor who those with hold I | 7 | | <--- a blank line here. 8 | ... elided paragraph last ... | 9 | | <--- a blank line here. 10 | Frost Robert ----------------------- | +----------------------------------------+ ;Cf. * [[Phrase reversals]]
puts <<EOS ---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert ----------------------- EOS .each_line.map {|line| line.split.reverse.join(' ')}
Roman numerals/Decode
Ruby
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any '''0'''s (zeroes). '''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and '''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII). The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
def fromRoman(roman) r = roman.upcase n = 0 until r.empty? do case when r.start_with?('M') then v = 1000; len = 1 when r.start_with?('CM') then v = 900; len = 2 when r.start_with?('D') then v = 500; len = 1 when r.start_with?('CD') then v = 400; len = 2 when r.start_with?('C') then v = 100; len = 1 when r.start_with?('XC') then v = 90; len = 2 when r.start_with?('L') then v = 50; len = 1 when r.start_with?('XL') then v = 40; len = 2 when r.start_with?('X') then v = 10; len = 1 when r.start_with?('IX') then v = 9; len = 2 when r.start_with?('V') then v = 5; len = 1 when r.start_with?('IV') then v = 4; len = 2 when r.start_with?('I') then v = 1; len = 1 else raise ArgumentError.new("invalid roman numerals: " + roman) end n += v r.slice!(0,len) end n end [ "MCMXC", "MMVIII", "MDCLXVI" ].each {|r| p r => fromRoman(r)}
Roman numerals/Encode
Ruby
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: * 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC * 2008 is written as 2000=MM, 8=VIII; or MMVIII * 1666 uses each Roman symbol in descending order: MDCLXVI
Symbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' } Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ] def roman(num) return Symbols[num] if Symbols.has_key?(num) Subtractors.each do |cutPoint, subtractor| return roman(cutPoint) + roman(num - cutPoint) if num > cutPoint return roman(subtractor) + roman(num + subtractor) if num >= cutPoint - subtractor and num < cutPoint end end [1990, 2008, 1666].each do |i| puts "%4d => %s" % [i, roman(i)] end
Runge-Kutta method
Ruby
Given the example Differential equation: :y'(t) = t \times \sqrt {y(t)} With initial condition: :t_0 = 0 and y_0 = y(t_0) = y(0) = 1 This equation has an exact solution: :y(t) = \tfrac{1}{16}(t^2 +4)^2 ;Task Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation. * Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given) * Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution. ;Method summary Starting with a given y_n and t_n calculate: :\delta y_1 = \delta t\times y'(t_n, y_n)\quad :\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1) :\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2) :\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad then: :y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4) :t_{n+1} = t_n + \delta t\quad
def calc_rk4(f) return ->(t,y,dt){ ->(dy1 ){ ->(dy2 ){ ->(dy3 ){ ->(dy4 ){ ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 }.call( dt * f.call( t + dt , y + dy3 ))}.call( dt * f.call( t + dt/2, y + dy2/2 ))}.call( dt * f.call( t + dt/2, y + dy1/2 ))}.call( dt * f.call( t , y ))} end TIME_MAXIMUM, WHOLE_TOLERANCE = 10.0, 1.0e-5 T_START, Y_START, DT = 0.0, 1.0, 0.10 def my_diff_eqn(t,y) ; t * Math.sqrt(y) ; end def my_solution(t ) ; (t**2 + 4)**2 / 16 ; end def find_error(t,y) ; (y - my_solution(t)).abs ; end def is_whole?(t ) ; (t.round - t).abs < WHOLE_TOLERANCE ; end dy = calc_rk4( ->(t,y){my_diff_eqn(t,y)} ) t, y = T_START, Y_START while t <= TIME_MAXIMUM printf("y(%4.1f)\t= %12.6f \t error: %12.6e\n",t,y,find_error(t,y)) if is_whole?(t) t, y = t + DT, y + dy.call(t,y,DT) end
Runtime evaluation
Ruby
Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].
def first(main_var, main_binding) foo = 42 second [[main_var, main_binding], ["foo", binding]] end def second(args) sqr = lambda {|x| x**2} deref(args << ["sqr", binding]) end def deref(stuff) stuff.each do |varname, context| puts "value of #{varname} is #{eval varname, context}" end end hello = "world" first "hello", binding
Runtime evaluation/In an environment
Ruby
Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it. Do so in a way which: * does not involve string manipulation of the input source code * is plausibly extensible to a runtime-chosen set of bindings rather than just x * does not make x a ''global'' variable or note that these are impossible. ;See also: * For more general examples and language-specific details, see [[Eval]]. * [[Dynamic variable names]] is a similar task.
def bind_x_to_value(x) binding end def eval_with_x(code, a, b) eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a)) end puts eval_with_x('2 ** x', 3, 5) # Prints "24"
SHA-1
Ruby
'''SHA-1''' or '''SHA1''' is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government standard, FIPS 180-1, defines SHA-1. Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. {{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}
require 'stringio' # Calculates SHA-1 message digest of _string_. Returns binary digest. # For hexadecimal digest, use +*sha1(string).unpack('H*')+. #-- # This is a simple, pure-Ruby implementation of SHA-1, following # the algorithm in FIPS 180-1. #++ def sha1(string) # functions and constants mask = 0xffffffff s = proc{|n, x| ((x << n) & mask) | (x >> (32 - n))} f = [ proc {|b, c, d| (b & c) | (b.^(mask) & d)}, proc {|b, c, d| b ^ c ^ d}, proc {|b, c, d| (b & c) | (b & d) | (c & d)}, proc {|b, c, d| b ^ c ^ d}, ].freeze k = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6].freeze # initial hash h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0] bit_len = string.size << 3 string += "\x80" while (string.size % 64) != 56 string += "\0" end string = string.force_encoding('ascii-8bit') + [bit_len >> 32, bit_len & mask].pack("N2") if string.size % 64 != 0 fail "failed to pad to correct length" end io = StringIO.new(string) block = "" while io.read(64, block) w = block.unpack("N16") # Process block. (16..79).each {|t| w[t] = s[1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]]} a, b, c, d, e = h t = 0 4.times do |i| 20.times do temp = (s[5, a] + f[i][b, c, d] + e + w[t] + k[i]) & mask a, b, c, d, e = temp, a, s[30, b], c, d t += 1 end end [a,b,c,d,e].each_with_index {|x,i| h[i] = (h[i] + x) & mask} end h.pack("N5") end if __FILE__ == $0 # Print some example SHA-1 digests. # FIPS 180-1 has correct digests for 'abc' and 'abc...opq'. [ 'abc', 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', 'Rosetta Code', ].each {|s| printf("%s:\n %s\n", s, *sha1(s).unpack('H*'))} end
Sailors, coconuts and a monkey problem
Ruby
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) ;The task: # Calculate the minimum possible size of the initial pile of coconuts collected during the first day. # Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.) # Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). # Show your answers here. ;Extra credit (optional): * Give some indication of the number of coconuts each sailor hides during the night. ;Note: * Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. * The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale! ;C.f: * Monkeys and Coconuts - Numberphile (Video) Analytical solution. * A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
def valid?(sailor, nuts) sailor.times do return false if (nuts % sailor) != 1 nuts -= 1 + nuts / sailor end nuts > 0 and nuts % sailor == 0 end [5,6].each do |sailor| n = sailor n += 1 until valid?(sailor, n) puts "\n#{sailor} sailors => #{n} coconuts" (sailor+1).times do div, mod = n.divmod(sailor) puts " #{[n, div, mod]}" n -= 1 + div end end
Sailors, coconuts and a monkey problem
Ruby 2.1+
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) ;The task: # Calculate the minimum possible size of the initial pile of coconuts collected during the first day. # Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.) # Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). # Show your answers here. ;Extra credit (optional): * Give some indication of the number of coconuts each sailor hides during the night. ;Note: * Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. * The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale! ;C.f: * Monkeys and Coconuts - Numberphile (Video) Analytical solution. * A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
def coconuts(sailor) sailor.step(by:sailor) do |nuts| flag = sailor.times do break if nuts % (sailor-1) != 0 nuts += nuts / (sailor-1) + 1 end return nuts if flag end end (2..9).each do |sailor| puts "#{sailor}: #{coconuts(sailor)}" end
Selectively replace multiple instances of a character within a string
Ruby
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: * the first 'a' with 'A' * the second 'a' with 'B' * the fourth 'a' with 'C' * the fifth 'a' with 'D' * the first 'b' with 'E' * the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD".
str = "abracadabra" rules = [ ["a", 1, "A"], ["a", 2, "B"], ["a", 4, "C"], ["a", 5, "D"], ["b", 1, "E"], ["r", 2, "F"]] indices = Hash.new{[]} str.each_char.with_index{|c, i| indices[c] <<= i} rules.each{|char, i, to| str[indices[char][i-1]] = to} p str
Self-describing numbers
Ruby
{{task}}There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example, '''2020''' is a four-digit self describing number: * position 0 has value 2 and there are two 0s in the number; * position 1 has value 0 and there are no 1s in the number; * position 2 has value 2 and there are two 2s; * position 3 has value 0 and there are zero 3s. Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000. ;Task Description # Write a function/routine/method/... that will check whether a given positive integer is self-describing. # As an optional stretch goal - generate and display the set of self-describing numbers. ;Related tasks: * [[Fours is the number of letters in the ...]] * [[Look-and-say sequence]] * [[Number names]] * [[Self-referential sequence]] * [[Spelling of ordinal numbers]]
def self_describing?(n) digits = n.digits.reverse digits.each_with_index.all?{|digit, idx| digits.count(idx) == digit} end 3_300_000.times {|n| puts n if self_describing?(n)}
Self-describing numbers
Ruby from Wren
{{task}}There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example, '''2020''' is a four-digit self describing number: * position 0 has value 2 and there are two 0s in the number; * position 1 has value 0 and there are no 1s in the number; * position 2 has value 2 and there are two 2s; * position 3 has value 0 and there are zero 3s. Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000. ;Task Description # Write a function/routine/method/... that will check whether a given positive integer is self-describing. # As an optional stretch goal - generate and display the set of self-describing numbers. ;Related tasks: * [[Fours is the number of letters in the ...]] * [[Look-and-say sequence]] * [[Number names]] * [[Self-referential sequence]] * [[Spelling of ordinal numbers]]
def selfDesc(n) ns = n.to_s nc = ns.size count = Array.new(nc, 0) sum = 0 while n > 0 d = n % 10 return false if d >= nc # can't have a digit >= number of digits sum += d return false if sum > nc count[d] += 1 n /= 10 end # to be self-describing sum of digits must equal number of digits return false if sum != nc return ns == count.join() # there must always be at least one zero end start = Time.now print("The self-describing numbers are:") i = 10 # self-describing number must end in 0 pw = 10 # power of 10 fd = 1 # first digit sd = 1 # second digit dg = 2 # number of digits mx = 11 # maximum for current batch lim = 9_100_000_001 # sum of digits can't be more than 10 while i < lim if selfDesc(i) secs = (Time.now - start) #.total_seconds print("\n#{i} in #{secs} secs") end i += 10 if i > mx fd += 1 sd -= 1 if sd >= 0 i = pw * fd else pw *= 10 dg += 1 i = pw fd = 1 sd = dg - 1 end mx = i + sd * pw / 10 end end osecs = (Time.now - start) print("\nTook #{osecs} secs overall")
Semordnilap
Ruby
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: ''lager'' and ''regal'' ;Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.)
dict = File.readlines("unixdict.txt").collect(&:strip) i = 0 res = dict.collect(&:reverse).sort.select do |z| i += 1 while z > dict[i] and i < dict.length-1 z == dict[i] and z < z.reverse end puts "There are #{res.length} semordnilaps, of which the following are 5:" res.take(5).each {|z| puts "#{z} #{z.reverse}"}
Sequence: nth number with exactly n divisors
Ruby from Java
Calculate the sequence where each term an is the nth that has '''n''' divisors. ;Task Show here, on this page, at least the first '''15''' terms of the sequence. ;See also :*OEIS:A073916 ;Related tasks :*[[Sequence: smallest number greater than previous term with exactly n divisors]] :*[[Sequence: smallest number with exactly n divisors]]
def isPrime(n) return false if n < 2 return n == 2 if n % 2 == 0 return n == 3 if n % 3 == 0 k = 5 while k * k <= n return false if n % k == 0 k = k + 2 end return true end def getSmallPrimes(numPrimes) smallPrimes = [2] count = 0 n = 3 while count < numPrimes if isPrime(n) then smallPrimes << n count = count + 1 end n = n + 2 end return smallPrimes end def getDivisorCount(n) count = 1 while n % 2 == 0 n = (n / 2).floor count = count + 1 end d = 3 while d * d <= n q = (n / d).floor r = n % d dc = 0 while r == 0 dc = dc + count n = q q = (n / d).floor r = n % d end count = count + dc d = d + 2 end if n != 1 then count = 2 * count end return count end MAX = 15 @smallPrimes = getSmallPrimes(MAX) def OEISA073916(n) if isPrime(n) then return @smallPrimes[n - 1] ** (n - 1) end count = 0 result = 0 i = 1 while count < n if n % 2 == 1 then # The solution for an odd (non-prime) term is always a square number root = Math.sqrt(i) if root * root != i then i = i + 1 next end end if getDivisorCount(i) == n then count = count + 1 result = i end i = i + 1 end return result end n = 1 while n <= MAX print "A073916(", n, ") = ", OEISA073916(n), "\n" n = n + 1 end
Sequence: smallest number greater than previous term with exactly n divisors
Ruby
Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors. ;Task Show here, on this page, at least the first '''15''' terms of the sequence. ;See also :* OEIS:A069654 ;Related tasks :* [[Sequence: smallest number with exactly n divisors]] :* [[Sequence: nth number with exactly n divisors]]
require 'prime' def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end seq = Enumerator.new do |y| cur = 0 (1..).each do |i| if num_divisors(i) == cur + 1 then y << i cur += 1 end end end p seq.take(15)
Sequence: smallest number with exactly n divisors
Ruby
Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors. ;Task Show here, on this page, at least the first '''15''' terms of the sequence. ;Related tasks: :* [[Sequence: smallest number greater than previous term with exactly n divisors]] :* [[Sequence: nth number with exactly n divisors]] ;See also: :* OEIS:A005179
require 'prime' def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end def first_with_num_divs(n) (1..).detect{|i| num_divisors(i) == n } end p (1..15).map{|n| first_with_num_divs(n) }
Set consolidation
Ruby
Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is: * The two input sets if no common item exists between the two input sets of items. * The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. ;'''Example 1:''' :Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. ;'''Example 2:''' :Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). ;'''Example 3:''' :Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} ;'''Example 4:''' :The consolidation of the five sets: ::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} :Is the two sets: ::{A, C, B, D}, and {G, F, I, H, K} '''See also''' * Connected component (graph theory) * [[Range consolidation]]
require 'set' tests = [[[:A,:B], [:C,:D]], [[:A,:B], [:B,:D]], [[:A,:B], [:C,:D], [:D,:B]], [[:H,:I,:K], [:A,:B], [:C,:D], [:D,:B], [:F,:G,:H]]] tests.map!{|sets| sets.map(&:to_set)} tests.each do |sets| until sets.combination(2).none?{|a,b| a.merge(b) && sets.delete(b) if a.intersect?(b)} end p sets end
Set of real numbers
Ruby 1.9.3
All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of "between", depending on open or closed boundary: * [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' } * (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' } * [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' } * (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' } Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty. '''Task''' * Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. * Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets): :* ''x'' ''A'': determine if ''x'' is an element of ''A'' :: example: 1 is in [1, 2), while 2, 3, ... are not. :* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''} :: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3] :* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''} :: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set :* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''} :: example: [0, 2) - (1, 3) = [0, 1] * Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: :* (0, 1] [0, 2) :* [0, 2) (1, 2] :* [0, 3) - (0, 1) :* [0, 3) - [0, 1] '''Implementation notes''' * 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. * Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. * You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). '''Optional work''' * Create a function to determine if a given set is empty (contains no element). * Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that |sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.
class Rset Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do def include?(x) (inc_lo ? lo<=x : lo<x) and (inc_hi ? x<=hi : x<hi) end def length hi - lo end def to_s "#{inc_lo ? '[' : '('}#{lo},#{hi}#{inc_hi ? ']' : ')'}" end end def initialize(lo=nil, hi=nil, inc_lo=false, inc_hi=false) if lo.nil? and hi.nil? @sets = [] # empty set else raise TypeError unless lo.is_a?(Numeric) and hi.is_a?(Numeric) raise ArgumentError unless valid?(lo, hi, inc_lo, inc_hi) @sets = [Set[lo, hi, !!inc_lo, !!inc_hi]] # !! -> Boolean values end end def self.[](lo, hi, inc_hi=true) self.new(lo, hi, true, inc_hi) end def self.parse(str) raise ArgumentError unless str =~ /(\[|\()(.+),(.+)(\]|\))/ b0, lo, hi, b1 = $~.captures # $~ : Regexp.last_match lo = Rational(lo) lo = lo.numerator if lo.denominator == 1 hi = Rational(hi) hi = hi.numerator if hi.denominator == 1 self.new(lo, hi, b0=='[', b1==']') end def initialize_copy(obj) super @sets = @sets.map(&:dup) end def include?(x) @sets.any?{|set| set.include?(x)} end def empty? @sets.empty? end def union(other) sets = (@sets+other.sets).map(&:dup).sort_by{|set| [set.lo, set.hi]} work = [] pre = sets.shift sets.each do |post| if valid?(pre.hi, post.lo, !pre.inc_hi, !post.inc_lo) work << pre pre = post else pre.inc_lo |= post.inc_lo if pre.lo == post.lo if pre.hi < post.hi pre.hi = post.hi pre.inc_hi = post.inc_hi elsif pre.hi == post.hi pre.inc_hi |= post.inc_hi end end end work << pre if pre new_Rset(work) end alias | union def intersection(other) sets = @sets.map(&:dup) work = [] other.sets.each do |oset| sets.each do |set| if set.hi < oset.lo or oset.hi < set.lo # ignore elsif oset.lo < set.lo and set.hi < oset.hi work << set else lo = [set.lo, oset.lo].max if set.lo == oset.lo inc_lo = set.inc_lo && oset.inc_lo else inc_lo = (set.lo < oset.lo) ? oset.inc_lo : set.inc_lo end hi = [set.hi, oset.hi].min if set.hi == oset.hi inc_hi = set.inc_hi && oset.inc_hi else inc_hi = (set.hi < oset.hi) ? set.inc_hi : oset.inc_hi end work << Set[lo, hi, inc_lo, inc_hi] if valid?(lo, hi, inc_lo, inc_hi) end end end new_Rset(work) end alias & intersection def difference(other) sets = @sets.map(&:dup) other.sets.each do |oset| work = [] sets.each do |set| if set.hi < oset.lo or oset.hi < set.lo work << set elsif oset.lo < set.lo and set.hi < oset.hi # delete else if set.lo < oset.lo inc_hi = (set.hi==oset.lo and !set.inc_hi) ? false : !oset.inc_lo work << Set[set.lo, oset.lo, set.inc_lo, inc_hi] elsif valid?(set.lo, oset.lo, set.inc_lo, !oset.inc_lo) work << Set[set.lo, set.lo, true, true] end if oset.hi < set.hi inc_lo = (oset.hi==set.lo and !set.inc_lo) ? false : !oset.inc_hi work << Set[oset.hi, set.hi, inc_lo, set.inc_hi] elsif valid?(oset.hi, set.hi, !oset.inc_hi, set.inc_hi) work << Set[set.hi, set.hi, true, true] end end end sets = work end new_Rset(sets) end alias - difference # symmetric difference def ^(other) (self - other) | (other - self) end def ==(other) self.class == other.class and @sets == other.sets end def length @sets.inject(0){|len, set| len + set.length} end def to_s "#{self.class}#{@sets.join}" end alias inspect to_s protected attr_accessor :sets private def new_Rset(sets) rset = self.class.new # empty set rset.sets = sets rset end def valid?(lo, hi, inc_lo, inc_hi) lo < hi or (lo==hi and inc_lo and inc_hi) end end def Rset(lo, hi, inc_hi=false) Rset.new(lo, hi, false, inc_hi) end
Set of real numbers
Ruby 2.1+
All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of "between", depending on open or closed boundary: * [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' } * (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' } * [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' } * (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' } Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty. '''Task''' * Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. * Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets): :* ''x'' ''A'': determine if ''x'' is an element of ''A'' :: example: 1 is in [1, 2), while 2, 3, ... are not. :* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''} :: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3] :* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''} :: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set :* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''} :: example: [0, 2) - (1, 3) = [0, 1] * Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: :* (0, 1] [0, 2) :* [0, 2) (1, 2] :* [0, 3) - (0, 1) :* [0, 3) - [0, 1] '''Implementation notes''' * 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. * Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. * You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). '''Optional work''' * Create a function to determine if a given set is empty (contains no element). * Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that |sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.
str, e = "e = Rset.new", nil puts "#{str} -> #{eval(str)}\t\t# create empty set" str = "e.empty?" puts "#{str} -> #{eval(str)}" puts include Math lohi = Enumerator.new do |y| t = 1 / sqrt(6) 0.step do |n| y << [sqrt(12*n+1) * t, sqrt(12*n+5) * t] y << [sqrt(12*n+7) * t, sqrt(12*n+11) * t] end end a = Rset.new loop do lo, hi = lohi.next break if 10 <= lo a |= Rset(lo, hi) end a &= Rset(0,10) b = (0...10).inject(Rset.new){|res,i| res |= Rset(i+1/6r,i+5/6r)} puts "a : #{a}" puts "a.length : #{a.length}" puts "b : #{b}" puts "b.length : #{b.length}" puts "a - b : #{a - b}" puts "(a-b).length : #{(a-b).length}"
Shoelace formula for polygonal area
Ruby
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) ;Task: Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area # => 30.0
Shortest common supersequence
Ruby from Tcl
The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task. ;;Task: Given two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique. Demonstrate this by printing s where u = "abcbdab" and v = "bdcaba". ;Also see: * Wikipedia: shortest common supersequence
require 'lcs' def scs(u, v) lcs = lcs(u, v) u, v = u.dup, v.dup scs = "" # Iterate over the characters until LCS processed until lcs.empty? if u[0]==lcs[0] and v[0]==lcs[0] # Part of the LCS, so consume from all strings scs << lcs.slice!(0) u.slice!(0) v.slice!(0) elsif u[0]==lcs[0] # char of u = char of LCS, but char of LCS v doesn't so consume just that scs << v.slice!(0) else # char of u != char of LCS, so consume just that scs << u.slice!(0) end end # append remaining characters, which are not in common scs + u + v end u = "abcbdab" v = "bdcaba" puts "SCS(#{u}, #{v}) = #{scs(u, v)}"
Show ASCII table
Ruby
Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.
chars = (32..127).map do |ord| k = case ord when 32 then "␠" when 127 then "␡" else ord.chr end "#{ord.to_s.ljust(3)}: #{k}" end chars.each_slice(chars.size/6).to_a.transpose.each{|s| puts s.join(" ")}
Show the epoch
Ruby
Choose popular date libraries used by your language and show the epoch those libraries use. A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. ;Related task: * [[Date format]]
require "date" Date.new # => #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>
Smallest number k such that k+2^m is composite for all m less than k
Ruby
Generate the sequence of numbers '''a(k)''', where each '''k''' is the smallest positive integer such that '''k + 2m''' is composite for every positive integer '''m''' less than '''k'''. ;For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not an element of this sequence. It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite. ;Task Find and display, here on this page, the first '''5''' elements of this sequence. ;See also OEIS:A033919 - Odd k for which k+2^m is composite for all m < k
require 'openssl' a = (1..).step(2).lazy.select do |k| next if k == 1 (1..(k-1)).none? {|m| OpenSSL::BN.new(k+(2**m)).prime?} end p a.first 5
Smith numbers
Ruby
sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are ''excluded'' as they (naturally) satisfy this condition! Smith numbers are also known as ''joke'' numbers. ;Example Using the number '''166''' Find the prime factors of '''166''' which are: '''2''' x '''83''' Then, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13''' Then, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13''' Therefore, the number '''166''' is a Smith number. ;Task Write a program to find all Smith numbers ''below'' 10000. ;See also * from Wikipedia: [Smith number]. * from MathWorld: [Smith number]. * from OEIS A6753: [OEIS sequence A6753]. * from OEIS A104170: [Number of Smith numbers below 10^n]. * from The Prime pages: [Smith numbers].
require "prime" class Integer def smith? return false if prime? digits.sum == prime_division.map{|pr,n| pr.digits.sum * n}.sum end end n = 10_000 res = 1.upto(n).select(&:smith?) puts "#{res.size} smith numbers below #{n}: #{res.first(5).join(", ")},... #{res.last(5).join(", ")}"
Solve a Hidato puzzle
Ruby
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: * You are given a grid with some numbers placed in it. The other squares in the grid will be blank. ** The grid is not necessarily rectangular. ** The grid may have holes in it. ** The grid is always connected. ** The number "1" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. ** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. * The aim is to place a natural number in each blank square so that in the sequence of numbered squares from "1" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). ** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. ** A square may only contain one number. * In a proper Hidato puzzle, the solution is unique. For example the following problem Sample Hidato problem, from Wikipedia has the following solution, with path marked on it: Solution to sample Hidato problem ;Related tasks: * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Holy Knight's tour]] * [[Solve a Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]];
# Solve a Hidato Puzzle # class Hidato Cell = Struct.new(:value, :used, :adj) ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] def initialize(board, pout=true) @board = [] board.each_line do |line| @board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil] end @board << [] # frame (Sentinel value : nil) @board.each_with_index do |row, x| row.each_with_index do |cell, y| if cell @sx, @sy = x, y if cell.value==1 # start position cell.adj = ADJUST.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]} end end end @xmax = @board.size - 1 @ymax = @board.map(&:size).max - 1 @end = @board.flatten.compact.size puts to_s('Problem:') if pout end def solve @zbl = Array.new(@end+1, false) @board.flatten.compact.each{|cell| @zbl[cell.value] = true} puts (try(@board[@sx][@sy], 1) ? to_s('Solution:') : "No solution") end def try(cell, seq_num) return true if seq_num > @end return false if cell.used value = cell.value return false if value > 0 and value != seq_num return false if value == 0 and @zbl[seq_num] cell.used = true cell.adj.each do |x, y| if try(@board[x][y], seq_num+1) cell.value = seq_num return true end end cell.used = false end def to_s(msg=nil) str = (0...@xmax).map do |x| (0...@ymax).map{|y| "%3s" % ((c=@board[x][y]) ? c.value : c)}.join end (msg ? [msg] : []) + str + [""] end end
Solve a Holy Knight's tour
Ruby
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: ;Example: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. ;Related tasks: * [[A* search algorithm]] * [[Knight's tour]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 EOS t0 = Time.now HLPsolver.new(boardy).solve puts " #{Time.now - t0} sec"
Solve a Hopido puzzle
Ruby
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7x7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . Extra credits are available for other interesting designs. ;Related tasks: * [[A* search algorithm]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
require 'HLPsolver' ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]] board1 = <<EOS . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . EOS t0 = Time.now HLPsolver.new(board1).solve puts " #{Time.now - t0} sec"
Solve a Numbrix puzzle
Ruby
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: ;Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 ;Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 ;Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. ;Related tasks: * [[A* search algorithm]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve the no connection puzzle]]
require 'HLPsolver' ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]] board1 = <<EOS 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 EOS HLPsolver.new(board1).solve board2 = <<EOS 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 EOS HLPsolver.new(board2).solve
Sparkline in unicode
Ruby from Raku
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. ;Task: Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a sparkline-type bar graph of the values on a single line of output. The eight characters: '########' (Unicode values U+2581 through U+2588). Use your program to show sparklines for the following input, here on this page: # 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 # 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 :(note the mix of separators in this second case)! ;Notes: * A space is not part of the generated sparkline. * The sparkline may be accompanied by simple statistics of the data such as its range. * A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases: :: "0, 1, 19, 20" -> #### :: (Aiming to use just two spark levels) :: "0, 999, 4000, 4999, 7000, 7999" -> ###### :: (Aiming to use just three spark levels) :: It may be helpful to include these cases in output tests. * You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
bar = ('▁'..'█').to_a loop {print 'Numbers please separated by space/commas: ' numbers = gets.split(/[\s,]+/).map(&:to_f) min, max = numbers.minmax puts "min: %5f; max: %5f"% [min, max] div = (max - min) / (bar.size - 1) puts min == max ? bar.last*numbers.size : numbers.map{|num| bar[((num - min) / div).to_i]}.join }
Sphenic numbers
Ruby
Definitions A '''sphenic number''' is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below). For the purposes of this task, a '''sphenic triplet''' is a group of three sphenic numbers which are consecutive. Note that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct. ;Examples 30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one. [1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers. ;Task Calculate and show here: 1. All sphenic numbers less than 1,000. 2. All sphenic triplets less than 10,000. ;Stretch 3. How many sphenic numbers are there less than 1 million? 4. How many sphenic triplets are there less than 1 million? 5. What is the 200,000th sphenic number and its 3 prime factors? 6. What is the 5,000th sphenic triplet? Hint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6. ;References * Wikipedia: Sphenic number * OEIS:A007304 - Sphenic numbers * OEIS:A165936 - Sphenic triplets (in effect) ;Related tasks * [[Almost prime]] * [[Square-free integers]]
require 'prime' class Integer def sphenic? = prime_division.map(&:last) == [1, 1, 1] end sphenics = (1..).lazy.select(&:sphenic?) n = 1000 puts "Sphenic numbers less than #{n}:" p sphenics.take_while{|s| s < n}.to_a n = 10_000 puts "\nSphenic triplets less than #{n}:" sps = sphenics.take_while{|s| s < n}.to_a sps.each_cons(3).select{|a, b, c| a + 2 == c}.each{|ar| p ar} n = 1_000_000 sphenics_below10E6 = sphenics.take_while{|s| s < n}.to_a puts "\nThere are #{sphenics_below10E6.size} sphenic numbers below #{n}." target = sphenics_below10E6[200_000-1] puts "\nThe 200000th sphenic number is #{target} with factors #{target.prime_division.map(&:first)}." triplets = sphenics_below10E6.each_cons(3).select{|a,b,c|a+2 == c} puts "\nThe 5000th sphenic triplet is #{triplets[4999]}."
Split a character string based on change of character
Ruby
Split a (character) string into comma (plus a blank) delimited strings based on a change of character (left to right). Show the output here (use the 1st example below). Blanks should be treated as any other character (except they are problematic to display clearly). The same applies to commas. For instance, the string: gHHH5YY++///\ should be split and show: g, HHH, 5, YY, ++, ///, \
def split(str) puts " input string: #{str}" s = str.chars.chunk(&:itself).map{|_,a| a.join}.join(", ") puts "output string: #{s}" s end split("gHHH5YY++///\\")
Square-free integers
Ruby
Write a function to test if a number is ''square-free''. A ''square-free'' is an integer which is divisible by no perfect square other than '''1''' (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between: ::* '''1''' ---> '''145''' (inclusive) ::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive) (One trillion = 1,000,000,000,000) Show here (on this page) the count of square-free integers from: ::* '''1''' ---> one hundred (inclusive) ::* '''1''' ---> one thousand (inclusive) ::* '''1''' ---> ten thousand (inclusive) ::* '''1''' ---> one hundred thousand (inclusive) ::* '''1''' ---> one million (inclusive) ;See also: :* the Wikipedia entry: square-free integer
require "prime" class Integer def square_free? prime_division.none?{|pr, exp| exp > 1} end end puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(" ")} puts m = 10**12 puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(" ")} puts markers = [100, 1000, 10_000, 100_000, 1_000_000] count = 0 (1..1_000_000).each do |n| count += 1 if n.square_free? puts "#{count} square-frees upto #{n}" if markers.include?(n) end
Square but not cube
Ruby
Show the first '''30''' positive integers which are squares but not cubes of such integers. Optionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.
#!/usr/bin/env ruby class PowIt :next def initialize @next = 1; end end class SquareIt < PowIt def next result = @next ** 2 @next += 1 return result end end class CubeIt < PowIt def next result = @next ** 3 @next += 1 return result end end squares = [] hexponents = [] squit = SquareIt.new cuit = CubeIt.new s = squit.next c = cuit.next while (squares.length < 30 || hexponents.length < 3) if s < c squares.push(s) if squares.length < 30 s = squit.next elsif s == c hexponents.push(s) if hexponents.length < 3 s = squit.next c = cuit.next else c = cuit.next end end puts "Squares:" puts squares.join(" ") puts "Square-and-cubes:" puts hexponents.join(" ")
Stair-climbing puzzle
Ruby
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers? Here's a pseudo-code of a simple recursive solution without using variables: func step_up() { if not step() { step_up(); step_up(); } } Inductive proof that step_up() steps up one step, if it terminates: * Base case (if the step() call returns true): it stepped up one step. QED * Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED The second (tail) recursion above can be turned into an iteration, as follows: func step_up() { while not step() { step_up(); } }
def step_up start_position = $position step until ($position == start_position + 1) end # assumptions about the step function: # - it maintains the current position of the robot "as a side effect" # - the robot is equally likely to step back as to step up def step if rand < 0.5 $position -= 1 p "fall (#$position)" if $DEBUG return false else $position += 1 p "rise (#$position)" if $DEBUG return true end end $position = 0 step_up
Statistics/Normal distribution
Ruby 2.7
The derive normally distributed random numbers from a uniform generator. ;The task: # Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. # Mention any native language support for the generation of normally distributed random numbers. ;Reference: * You may refer to code in [[Statistics/Basic]] if available.
# Class to implement a Normal distribution, generated from a Uniform distribution. # Uses the Marsaglia polar method. class NormalFromUniform # Initialize an instance. def initialize() @next = nil end # Generate and return the next Normal distribution value. def rand() if @next retval, @next = @next, nil return retval else u = v = s = nil loop do u = Random.rand(-1.0..1.0) v = Random.rand(-1.0..1.0) s = u**2 + v**2 break if (s > 0.0) && (s <= 1.0) end f = Math.sqrt(-2.0 * Math.log(s) / s) @next = v * f return u * f end end end
Stern-Brocot sequence
Ruby 2.1
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]]. # The first and second members of the sequence are both 1: #* 1, 1 # Start by considering the second member of the sequence # Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence: #* 1, 1, 2 # Append the considered member of the sequence to the end of the sequence: #* 1, 1, 2, 1 # Consider the next member of the series, (the third member i.e. 2) # GOTO 3 #* #* --- Expanding another loop we get: --- #* # Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence: #* 1, 1, 2, 1, 3 # Append the considered member of the sequence to the end of the sequence: #* 1, 1, 2, 1, 3, 2 # Consider the next member of the series, (the fourth member i.e. 1) ;The task is to: * Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. * Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) * Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence. * Show the (1-based) index of where the number 100 first appears in the sequence. * Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. ;Related tasks: :* [[Fusc sequence]]. :* [[Continued fraction/Arithmetic]] ;Ref: * Infinite Fractions - Numberphile (Video). * Trees, Teeth, and Time: The mathematics of clock making. * A002487 The On-Line Encyclopedia of Integer Sequences.
def sb return enum_for :sb unless block_given? a=[1,1] 0.step do |i| yield a[i] a << a[i]+a[i+1] << a[i+1] end end puts "First 15: #{sb.first(15)}" [*1..10,100].each do |n| puts "#{n} first appears at #{sb.find_index(n)+1}." end if sb.take(1000).each_cons(2).all? { |a,b| a.gcd(b) == 1 } puts "All GCD's are 1" else puts "Whoops, not all GCD's are 1!" end
Stirling numbers of the first kind
Ruby from D
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of '''n''' elements with '''k''' disjoint cycles. Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials. Depending on the application, Stirling numbers of the first kind may be "signed" or "unsigned". Signed Stirling numbers of the first kind arise when the polynomial expansion is expressed in terms of falling factorials; unsigned when expressed in terms of rising factorials. The only substantial difference is that, for signed Stirling numbers of the first kind, values of S1(n, k) are negative when n + k is odd. Stirling numbers of the first kind follow the simple identities: S1(0, 0) = 1 S1(n, 0) = 0 if n > 0 S1(n, k) = 0 if k > n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned ''or'' S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed ;Task: :* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the first kind'''. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. :* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, '''S1(n, k)''', up to '''S1(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen. :* If your language supports large integers, find and show here, on this page, the maximum value of '''S1(n, k)''' where '''n == 100'''. ;See also: :* '''Wikipedia - Stirling numbers of the first kind''' :* '''OEIS:A008275 - Signed Stirling numbers of the first kind''' :* '''OEIS:A130534 - Unsigned Stirling numbers of the first kind''' ;Related Tasks: :* '''Stirling numbers of the second kind''' :* '''Lah numbers'''
$cache = {} def sterling1(n, k) if n == 0 and k == 0 then return 1 end if n > 0 and k == 0 then return 0 end if k > n then return 0 end key = [n, k] if $cache[key] then return $cache[key] end value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k) $cache[key] = value return value end MAX = 12 def main print "Unsigned Stirling numbers of the first kind:\n" print "n/k" for n in 0 .. MAX print "%10d" % [n] end print "\n" for n in 0 .. MAX print "%-3d" % [n] for k in 0 .. n print "%10d" % [sterling1(n, k)] end print "\n" end print "The maximum value of S1(100, k) =\n" previous = 0 for k in 1 .. 100 current = sterling1(100, k) if previous < current then previous = current else print previous, "\n" print "(%d digits, k = %d)\n" % [previous.to_s.length, k - 1] break end end end main()
Stirling numbers of the second kind
Ruby
Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to [[Bell numbers]], and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: S2(n, 0) and S2(0, k) = 0 # for n, k > 0 S2(n, n) = 1 S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1) ;Task: :* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the second kind'''. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. :* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, '''S2(n, k)''', up to '''S2(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n). :* If your language supports large integers, find and show here, on this page, the maximum value of '''S2(n, k)''' where '''n == 100'''. ;See also: :* '''Wikipedia - Stirling numbers of the second kind''' :* '''OEIS:A008277 - Stirling numbers of the second kind''' ;Related Tasks: :* '''Stirling numbers of the first kind''' :* '''Bell numbers''' :* '''Lah numbers'''
@memo = {} def sterling2(n, k) key = [n,k] return @memo[key] if @memo.key?(key) return 1 if n.zero? and k.zero? return 0 if n.zero? or k.zero? return 1 if n == k return 0 if k > n res = k * sterling2(n-1, k) + sterling2(n - 1, k-1) @memo[key] = res end r = (0..12) puts "Sterling2 numbers:" puts "n/k #{r.map{|n| "%11d" % n}.join}" r.each do |row| print "%-4s" % row puts "#{(0..row).map{|col| "%11d" % sterling2(row, col)}.join}" end puts "\nMaximum value from the sterling2(100, k)"; puts (1..100).map{|a| sterling2(100,a)}.max
Stream merge
Ruby
2-stream merge : Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. : Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. ; ''N''-stream merge : The same as above, but reading from ''N'' sources. : Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]]. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
def stream_merge(*files) fio = files.map{|fname| open(fname)} merge(fio.map{|io| [io, io.gets]}) end def merge(fdata) until fdata.empty? io, min = fdata.min_by{|_,data| data} puts min if (next_data = io.gets).nil? io.close fdata.delete([io, min]) else i = fdata.index{|x,_| x == io} fdata[i] = [io, next_data] end end end files = %w(temp1.dat temp2.dat temp3.dat) files.each do |fname| data = IO.read(fname).gsub("\n", " ") puts "#{fname}: #{data}" end stream_merge(*files)
Strip control codes and extended characters from a string
Ruby
Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results: :* a string with control codes stripped (but extended characters not stripped) :* a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
class String def strip_control_characters() chars.each_with_object("") do |char, str| str << char unless char.ascii_only? and (char.ord < 32 or char.ord == 127) end end def strip_control_and_extended_characters() chars.each_with_object("") do |char, str| str << char if char.ascii_only? and char.ord.between?(32,126) end end end p s = "\ba\x00b\n\rc\fd\xc3\x7ffoo" p s.strip_control_characters p s.strip_control_and_extended_characters
Subleq
Ruby
One-Instruction Set Computer (OISC). It is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. ;Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers. These integers may be interpreted in three ways: ::::* simple numeric values ::::* memory addresses ::::* characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows: :# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory. :# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''. :# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused. :# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused. :# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer. :# If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero). For purposes of this task, show the output of your solution when fed the below "Hello, world!" program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1 ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
class Computer def initialize program @memory = program.map &:to_i @instruction_pointer = 0 end def step return nil if @instruction_pointer < 0 a, b, c = @memory[@instruction_pointer .. @instruction_pointer + 2] @instruction_pointer += 3 if a == -1 b = readchar elsif b == -1 writechar @memory[a] else difference = @memory[b] -= @memory[a] @instruction_pointer = c if difference <= 0 end @instruction_pointer end def run current_pointer = @instruction_pointer current_pointer = step while current_pointer >= 0 end private def readchar gets[0].ord end def writechar code_point print code_point.chr end end subleq = Computer.new ARGV subleq.run