title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Convert decimal number to rational
Ruby 1.9+
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: * 67 / 74 = 0.9(054) = 0.9054054... * 14 / 27 = 0.(518) = 0.518518... Acceptable output: * 0.9054054 - 4527027 / 5000000 * 0.518518 - 259259 / 500000 Finite decimals are of course no problem: * 0.75 - 3 / 4
> '0.9054054 0.518518 0.75'.split.each { |d| puts "%s %s" % [d, Rational(d)] } 0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 => ["0.9054054", "0.518518", "0.75"]
Convert decimal number to rational
Ruby 2.1.0+
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: * 67 / 74 = 0.9(054) = 0.9054054... * 14 / 27 = 0.(518) = 0.518518... Acceptable output: * 0.9054054 - 4527027 / 5000000 * 0.518518 - 259259 / 500000 Finite decimals are of course no problem: * 0.75 - 3 / 4
A suffix for integer and float literals was introduced: 2.1.0p0 :001 > 0.9054054r => (4527027/5000000) 2.1.0p0 :002 > 0.518518r => (259259/500000) 2.1.0p0 :003 > 0.75r => (3/4)
Convert seconds to compound duration
Ruby
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrate that it passes the following three test-cases: '''''Test Cases''''' :::::{| class="wikitable" |- ! input number ! output string |- | 7259 | 2 hr, 59 sec |- | 86400 | 1 d |- | 6000000 | 9 wk, 6 d, 10 hr, 40 min |} '''''Details''''' The following five units should be used: :::::{| class="wikitable" |- ! unit ! suffix used in output ! conversion |- | week | wk | 1 week = 7 days |- | day | d | 1 day = 24 hours |- | hour | hr | 1 hour = 60 minutes |- | minute | min | 1 minute = 60 seconds |- | second | sec | |} However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
MINUTE = 60 HOUR = MINUTE*60 DAY = HOUR*24 WEEK = DAY*7 def sec_to_str(sec) w, rem = sec.divmod(WEEK) d, rem = rem.divmod(DAY) h, rem = rem.divmod(HOUR) m, s = rem.divmod(MINUTE) units = ["#{w} wk", "#{d} d", "#{h} h", "#{m} min", "#{s} sec"] units.reject{|str| str.start_with?("0")}.join(", ") end [7259, 86400, 6000000].each{|t| puts "#{t}\t: #{sec_to_str(t)}"}
Count the coins
Ruby
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and 5 pennies :::# A nickel and 10 pennies :::# 15 pennies ;Task: How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents). ;Optional: Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? (Note: the answer is larger than 232). ;References: * an algorithm from the book ''Structure and Interpretation of Computer Programs''. * an article in the algorithmist. * Change-making problem on Wikipedia.
def make_change(amount, coins) @cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)} @coins = coins do_count(amount, @coins.length - 1) end def do_count(n, m) if n < 0 || m < 0 0 elsif @cache[n][m] @cache[n][m] else @cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1) end end p make_change( 1_00, [1,5,10,25]) p make_change(1000_00, [1,5,10,25,50,100])
Create an HTML table
Ruby
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. * The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. * The numbers should be aligned in the same fashion for all columns.
def r rand(10000) end STDOUT << "".tap do |html| html << "<table>" [ ['X', 'Y', 'Z'], [r ,r ,r], [r ,r ,r], [r ,r ,r], [r ,r ,r] ].each_with_index do |row, index| html << "<tr>" html << "<td>#{index > 0 ? index : nil }</td>" html << row.map { |e| "<td>#{e}</td>"}.join html << "</tr>" end html << "</table>" end
Cullen and Woodall numbers
Ruby
A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number. A Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number. So for each '''n''' the associated Cullen number and Woodall number differ by 2. ''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.'' '''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime. It is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated. ;Task * Write procedures to find Cullen numbers and Woodall numbers. * Use those procedures to find and show here, on this page the first 20 of each. ;Stretch * Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''. * Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''. ;See also * OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1 * OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1 * OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime * OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
require 'openssl' cullen = Enumerator.new{|y| (1..).each{|n| y << (n*(1<<n) + 1)} } woodall = Enumerator.new{|y| (1..).each{|n| y << (n*(1<<n) - 1)} } cullen_primes = Enumerator.new{|y| (1..).each {|i|y << i if OpenSSL::BN.new(cullen.next).prime?}} woodall_primes = Enumerator.new{|y| (1..).each{|i|y << i if OpenSSL::BN.new(woodall.next).prime?}} num = 20 puts "First #{num} Cullen numbers:\n#{cullen.first(num).join(" ")}" puts "First #{num} Woodal numbers:\n#{woodall.first(num).join(" ")}" puts "First 5 Cullen primes:\n#{cullen_primes.first(5).join(", ")}" puts "First 12 Woodall primes:\n#{woodall_primes.first(12).join(", ")}"
Currency
Ruby
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. ;Note: The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact. For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. Use the values: ::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers) ::* 2 milkshakes at $2.86 each, and ::* a tax rate of 7.65%. (That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) Compute and output (show results on this page): ::* the total price before tax ::* the tax ::* the total with tax The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. The output must show dollars and cents with a decimal point. The three results displayed should be: ::* 22000000000000005.72 ::* 1683000000000000.44 ::* 23683000000000006.16 Dollar signs and thousands separators are optional.
require 'bigdecimal/util' before_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d tax = (before_tax * 0.0765.to_d).round(2) total = before_tax + tax puts "Before tax: $#{before_tax.to_s('F')} Tax: $#{tax.to_s('F')} Total: $#{total.to_s('F')}"
Currying
Ruby
{{Wikipedia|Currying}} ;Task: Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
b = proc {|x, y, z| (x||0) + (y||0) + (z||0) } p b.curry[1][2][3] #=> 6 p b.curry[1, 2][3, 4] #=> 6 p b.curry(5)[1][2][3][4][5] #=> 6 p b.curry(5)[1, 2][3, 4][5] #=> 6 p b.curry(1)[1] #=> 1 b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) } p b.curry[1][2][3] #=> 6 p b.curry[1, 2][3, 4] #=> 10 p b.curry(5)[1][2][3][4][5] #=> 15 p b.curry(5)[1, 2][3, 4][5] #=> 15 p b.curry(1)[1] #=> 1
Curzon numbers
Ruby
A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''. '''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''. ''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' Generalized Curzon numbers only exist for even base integers. ;Task * Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''. ;Stretch * Find and show the '''one thousandth'''. ;See also ;* Numbers Aplenty - Curzon numbers ;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers) ''and even though it is not specifically mentioned that they are Curzon numbers:'' ;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
def curzons(k) Enumerator.new do |y| (1..).each do |n| r = k * n y << n if k.pow(n, r + 1) == r end end end [2,4,6,8,10].each do |base| puts "Curzon numbers with k = #{base}:" puts curzons(base).take(50).join(", ") puts "Thousandth Curzon with k = #{base}: #{curzons(base).find.each.with_index(1){|_,i| i == 1000} }","" end
Cut a rectangle
Ruby from Python
A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below. [[file:rect-cut.svg]] Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts. Possibly related task: [[Maze generation]] for depth-first search.
def cut_it(h, w) if h.odd? return 0 if w.odd? h, w = w, h end return 1 if w == 1 nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] # [next,dy,dx] blen = (h + 1) * (w + 1) - 1 grid = [false] * (blen + 1) walk = lambda do |y, x, count=0| return count+1 if y==0 or y==h or x==0 or x==w t = y * (w + 1) + x grid[t] = grid[blen - t] = true nxt.each do |nt, dy, dx| count += walk[y + dy, x + dx] unless grid[t + nt] end grid[t] = grid[blen - t] = false count end t = h / 2 * (w + 1) + w / 2 if w.odd? grid[t] = grid[t + 1] = true count = walk[h / 2, w / 2 - 1] count + walk[h / 2 - 1, w / 2] * 2 else grid[t] = true count = walk[h / 2, w / 2 - 1] return count * 2 if h == w count + walk[h / 2 - 1, w / 2] end end for w in 1..9 for h in 1..w puts "%d x %d: %d" % [w, h, cut_it(w, h)] if (w * h).even? end end
Damm algorithm
Ruby
The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. ;Task: Verify the checksum, stored as last digit of an input.
TABLE = [ [0,3,1,7,5,9,8,6,4,2], [7,0,9,2,1,5,4,8,6,3], [4,2,0,6,8,7,1,3,5,9], [1,7,5,0,9,8,3,4,2,6], [6,1,2,3,0,4,5,9,7,8], [3,6,7,4,2,0,9,5,8,1], [5,8,6,9,7,2,0,1,3,4], [8,9,4,5,3,6,2,0,1,7], [9,4,3,8,6,1,7,2,0,5], [2,5,8,1,4,3,6,7,9,0] ] def damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| TABLE[idx][a] } == 0 [5724, 5727, 112946].each{|n| puts "#{n}: #{damm_valid?(n) ? "" : "in"}valid"}
De Bruijn sequences
Ruby from D
{{DISPLAYTITLE:de Bruijn sequences}} The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn. A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on a size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every possible length-''n'' string (computer science, formal theory) on ''A'' occurs exactly once as a contiguous substring. Such a sequence is denoted by ''B''(''k'', ''n'') and has length ''k''''n'', which is also the number of distinct substrings of length ''n'' on ''A''; de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1) / kn distinct de Bruijn sequences ''B''(''k'', ''n''). ;Task: For this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on a PIN-like code lock that does not have an "enter" key and accepts the last ''n'' digits entered. Note: automated teller machines (ATMs) used to work like this, but their software has been updated to not allow a brute-force attack. ;Example: A digital door lock with a 4-digit code would have ''B'' (10, 4) solutions, with a length of '''10,000''' (digits). Therefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to open the lock. Trying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses. ;Task requirements: :* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code. :::* Show the length of the generated de Bruijn sequence. :::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page). :::* Show the first and last '''130''' digits of the de Bruijn sequence. :* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence. :::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros). :* Reverse the de Bruijn sequence. :* Again, perform the (above) verification test. :* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence. :::* Perform the verification test (again). There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly. The verification processes should list any and all missing PIN codes.) Show all output here, on this page. ;References: :* Wikipedia entry: de Bruijn sequence. :* MathWorld entry: de Bruijn sequence. :* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
def deBruijn(k, n) alphabet = "0123456789" @a = Array.new(k * n, 0) @seq = [] def db(k, n, t, p) if t > n then if n % p == 0 then temp = @a[1 .. p] @seq.concat temp end else @a[t] = @a[t - p] db(k, n, t + 1, p) j = @a[t - p] + 1 while j < k do @a[t] = j # & 0xFF db(k, n, t + 1, t) j = j + 1 end end end db(k, n, 1, 1) buf = "" for i in @seq buf <<= alphabet[i] end return buf + buf[0 .. n-2] end def validate(db) le = db.length found = Array.new(10000, 0) errs = [] # Check all strings of 4 consecutive digits within 'db' # to see if all 10,000 combinations occur without duplication. for i in 0 .. le-4 s = db[i .. i+3] if s.scan(/\D/).empty? then found[s.to_i] += 1 end end for i in 0 .. found.length - 1 if found[i] == 0 then errs <<= (" PIN number %04d missing" % [i]) elsif found[i] > 1 then errs <<= (" PIN number %04d occurs %d times" % [i, found[i]]) end end if errs.length == 0 then print " No errors found\n" else pl = (errs.length == 1) ? "" : "s" print " ", errs.length, " error", pl, " found:\n" for err in errs print err, "\n" end end end db = deBruijn(10, 4) print "The length of the de Bruijn sequence is ", db.length, "\n\n" print "The first 130 digits of the de Bruijn sequence are: ", db[0 .. 129], "\n\n" print "The last 130 digits of the de Bruijn sequence are: ", db[-130 .. db.length], "\n\n" print "Validating the de Bruijn sequence:\n" validate(db) print "\n" db[4443] = '.' print "Validating the overlaid de Bruijn sequence:\n" validate(db)
Deceptive numbers
Ruby
Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation '''Rn''' symbolizes the repunit made up of '''n''' ones. Every prime '''p''' larger than 5, evenly divides the repunit '''Rp-1'''. ;E.G. The repunit '''R6''' is evenly divisible by '''7'''. 111111 / 7 = 15873 The repunit '''R42''' is evenly divisible by '''43'''. 111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677 And so on. There are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''. The repunit '''R90''' is evenly divisible by the composite number '''91''' (=7*13). 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221 ;Task * Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''Rn-1''' ;See also ;* Numbers Aplenty - Deceptive numbers ;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}
require 'prime' deceptives = Enumerator.new do |y| 10.step(by: 10) do |n| [1,3,7,9].each do |digit| cand = n + digit next if cand % 3 == 0 || cand.prime? repunit = ("1"*(cand-1)).to_i y << cand if (repunit % cand) == 0 end end end p deceptives.take(25).to_a
Deepcopy
Ruby
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: * Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. * Any limitations of the method. * That the structure and its copy are different. * Suitable links to external documentation for common libraries.
# _orig_ is a Hash that contains an Array. orig = { :num => 1, :ary => [2, 3] } orig[:cycle] = orig # _orig_ also contains itself. # _copy_ becomes a deep copy of _orig_. copy = Marshal.load(Marshal.dump orig) # These changes to _orig_ never affect _copy_, # because _orig_ and _copy_ are disjoint structures. orig[:ary] << 4 orig[:rng] = (5..6) # Because of deep copy, orig[:ary] and copy[:ary] # refer to different Arrays. p orig # => {:num=>1, :ary=>[2, 3, 4], :cycle=>{...}, :rng=>5..6} p copy # => {:num=>1, :ary=>[2, 3], :cycle=>{...}} # The original contains itself, and the copy contains itself, # but the original and the copy are not the same object. p [(orig.equal? orig[:cycle]), (copy.equal? copy[:cycle]), (not orig.equal? copy)] # => [true, true, true]
Deming's funnel
Ruby from Python
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target. * '''Rule 1''': The funnel remains directly above the target. * '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position. * '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target. * '''Rule 4''': The funnel is moved directly over the last place a marble landed. Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples. '''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed. '''Stretch goal 2''': Show scatter plots of all four results. ;Further information: * Further explanation and interpretation * Video demonstration of the funnel experiment at the Mayo Clinic.
def funnel(dxs, &rule) x, rxs = 0, [] for dx in dxs rxs << (x + dx) x = rule[x, dx] end rxs end def mean(xs) xs.inject(:+) / xs.size end def stddev(xs) m = mean(xs) Math.sqrt(xs.inject(0.0){|sum,x| sum + (x-m)**2} / xs.size) end def experiment(label, dxs, dys, &rule) rxs, rys = funnel(dxs, &rule), funnel(dys, &rule) puts label puts 'Mean x, y : %7.4f, %7.4f' % [mean(rxs), mean(rys)] puts 'Std dev x, y : %7.4f, %7.4f' % [stddev(rxs), stddev(rys)] puts end dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] experiment('Rule 1:', dxs, dys) {|z, dz| 0} experiment('Rule 2:', dxs, dys) {|z, dz| -dz} experiment('Rule 3:', dxs, dys) {|z, dz| -(z+dz)} experiment('Rule 4:', dxs, dys) {|z, dz| z+dz}
Department numbers
Ruby
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }
Descending primes
Ruby
Generate and show all primes with strictly descending decimal digits. ;See also ;* OEIS:A052014 - Primes with distinct digits in descending order ;Related: *[[Ascending primes]]
require 'prime' digits = [9,8,7,6,5,4,3,2,1].to_a res = 1.upto(digits.size).flat_map do |n| digits.combination(n).filter_map do |set| candidate = set.join.to_i candidate if candidate.prime? end.reverse end puts res.join(",")
Detect division by zero
Ruby
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
def div_check(x, y) begin x / y rescue ZeroDivisionError true else false end end
Detect division by zero
Ruby 1.9
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
def div_check(x, y) begin x.div y rescue ZeroDivisionError true else false end end
Determinant and permanent
Ruby
permanent of the matrix. The determinant is given by :: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i} while the permanent is given by :: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i} In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known. ;Related task: * [[Permutations by swapping]]
require 'matrix' class Matrix # Add "permanent" method to Matrix class def permanent r = (0...row_count).to_a # [0,1] (first example), [0,1,2,3] (second example) r.permutation.inject(0) do |sum, sigma| sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } end end end m1 = Matrix[[1,2],[3,4]] # testcases from Python version m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]] m3 = Matrix[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] [m1, m2, m3].each do |m| puts "determinant:\t #{m.determinant}", "permanent:\t #{m.permanent}" puts end
Determine if a string has all the same characters
Ruby
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pΓ©pΓ©", "🐢🐢🐺🐢", "πŸŽ„πŸŽ„πŸŽ„πŸŽ„"] strings.each do |str| pos = str.empty? ? nil : str =~ /[^#{str[0]}]/ print "#{str.inspect} (size #{str.size}): " puts pos ? "first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}." : "all the same." end
Determine if a string has all unique characters
Ruby
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as unique ::* process the strings from left-to-right ::* if unique, display a message saying such ::* if not unique, then: ::::* display a message saying such ::::* display what character is duplicated ::::* only the 1st non-unique character need be displayed ::::* display where "both" duplicated characters are in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the duplicated character Use (at least) these five test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 1 which is a single period ('''.''') :::* a string of length 6 which contains: '''abcABC''' :::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX''' :::* a string of length 36 which ''doesn't'' contain the letter "oh": :::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ''' Show all output here on this page.
strings = ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X", "hΓ©tΓ©rogΓ©nΓ©itΓ©", "πŸŽ†πŸŽƒπŸŽ‡πŸŽˆ", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ™Œ", "πŸ πŸŸπŸ‘πŸ¦ˆπŸ¬πŸ³πŸ‹πŸ‘",] strings.each do |str| seen = {} print "#{str.inspect} (size #{str.size}) " res = "has no duplicates." #may change str.chars.each_with_index do |c,i| if seen[c].nil? seen[c] = i else res = "has duplicate char #{c} (#{'%#x' % c.ord}) on #{seen[c]} and #{i}." break end end puts res end
Determine if a string is collapsible
Ruby
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ''immediately repeated'' character is any character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.} ;Examples: In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated by underscores (above), even though they (those characters) appear elsewhere in the character string. So, after ''collapsing'' the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate ''repeated'' characters and ''collapse'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: string number ++ 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | 5 | --- Harry S Truman | <###### has many repeated blanks +------------------------------------------------------------------------+
strings = ["", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ",] strings.each do |str| puts "«««#{str}»»» (size #{str.size})" ssq = str.squeeze puts "«««#{ssq}»»» (size #{ssq.size})" puts end
Determine if a string is squeezable
Ruby
Determine if a character string is ''squeezable''. And if so, squeeze the string (by removing any number of a ''specified'' ''immediately repeated'' character). This task is very similar to the task '''Determine if a character string is collapsible''' except that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''. If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). A specified ''immediately repeated'' character is any specified character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''squeeze'''.} ;Examples: In the following character string with a specified ''immediately repeated'' character of '''e''': The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''e''' is an specified repeated character, indicated by an underscore (above), even though they (the characters) appear elsewhere in the character string. So, after ''squeezing'' the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string, using a specified immediately repeated character '''s''': headmistressship The "squeezed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character and ''squeeze'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the specified repeated character (to be searched for and possibly ''squeezed''): :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: immediately string repeated number character ( | a blank, a minus, a seven, a period) ++ 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-' 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7' 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.' 5 | --- Harry S Truman | (below) <###### has many repeated blanks +------------------------------------------------------------------------+ | | | For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: * a blank * a minus * a lowercase '''r''' Note: there should be seven results shown, one each for the 1st four strings, and three results for the 5th string.
strings = ["", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "πŸ˜πŸ˜€πŸ™ŒπŸ’ƒπŸ˜πŸ˜πŸ˜πŸ™Œ",] squeeze_these = ["", "-", "7", ".", " -r", "😍"] strings.zip(squeeze_these).each do |str, st| puts "original: «««#{str}»»» (size #{str.size})" st.chars.each do |c| ssq = str.squeeze(c) puts "#{c.inspect}-squeezed: «««#{ssq}»»» (size #{ssq.size})" end puts end
Determine if two triangles overlap
Ruby from C
Determining if two triangles in the same plane overlap is an important topic in collision detection. ;Task: Determine which of these pairs of triangles overlap in 2D: :::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6) :::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0) :::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6) :::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4) :::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2) :::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer): :::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) # Triangles must be expressed anti-clockwise checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then # Points on the boundary are considered as colliding chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else # Points on the boundary are not considered as colliding chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end # For edge E of triangle 1 for i in 0..2 do j = (i + 1) % 3 # Check all points of trangle 2 lay on the external side of the edge E. If # they do, the triangles do not collide. if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end # For edge E of triangle 2 for i in 0..2 do j = (i + 1) % 3 # Check all points of trangle 1 lay on the external side of the edge E. If # they do, the triangles do not collide. if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end # The triangles collide return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] # Barely touching t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] # Barely touching t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
Dice game probabilities
Ruby
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
def roll_dice(n_dice, n_faces) return [[0,1]] if n_dice.zero? one = [1] * n_faces zero = [0] * (n_faces-1) (1...n_dice).inject(one){|ary,_| (zero + ary + zero).each_cons(n_faces).map{|a| a.inject(:+)} }.map.with_index(n_dice){|n,sum| [sum,n]} # sum: total of the faces end def game(dice1, faces1, dice2, faces2) p1 = roll_dice(dice1, faces1) p2 = roll_dice(dice2, faces2) p1.product(p2).each_with_object([0,0,0]) do |((sum1, n1), (sum2, n2)), win| win[sum1 <=> sum2] += n1 * n2 # [0]:draw, [1]:win, [-1]:lose end end [[9, 4, 6, 6], [5, 10, 6, 7]].each do |d1, f1, d2, f2| puts "player 1 has #{d1} dice with #{f1} faces each" puts "player 2 has #{d2} dice with #{f2} faces each" win = game(d1, f1, d2, f2) sum = win.inject(:+) puts "Probability for player 1 to win: #{win[1]} / #{sum}", " -> #{win[1].fdiv(sum)}", "" end
Digital root
Ruby
The digital root, X, of a number, n, is calculated: : find X as the sum of the digits of n : find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: :627615 has additive persistence 2 and digital root of 9; :39390 has additive persistence 2 and digital root of 6; :588225 has additive persistence 2 and digital root of 3; :393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. ;See: * [[Casting out nines]] for this wiki's use of this procedure. * [[Digital root/Multiplicative digital root]] * [[Sum digits of an integer]] * Digital root sequence on OEIS * Additive persistence sequence on OEIS * [[Iterated digits squaring]]
class String def digroot_persistence(base=10) num = self.to_i(base) persistence = 0 until num < base do num = num.digits(base).sum persistence += 1 end [num.to_s(base), persistence] end end puts "--- Examples in 10-Base ---" %w(627615 39390 588225 393900588225).each do |str| puts "%12s has a digital root of %s and a persistence of %s." % [str, *str.digroot_persistence] end puts "\n--- Examples in other Base ---" format = "%s base %s has a digital root of %s and a persistence of %s." [["101101110110110010011011111110011000001", 2], [ "5BB64DFCC1", 16], ["5", 8], ["50YE8N29", 36]].each do |(str, base)| puts format % [str, base, *str.digroot_persistence(base)] end
Disarium numbers
Ruby
A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. ;E.G. '''135''' is a '''Disarium number''': 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of '''Disarium numbers'''. ;Task * Find and display the first 18 '''Disarium numbers'''. ;Stretch * Find and display all 20 '''Disarium numbers'''. ;See also ;* Geeks for Geeks - Disarium numbers ;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) ;* Related task: Narcissistic decimal number ;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
disariums = Enumerator.new do |y| (0..).each do |n| i = 0 y << n if n.digits.reverse.sum{|d| d ** (i+=1) } == n end end puts disariums.take(19).to_a.join(" ")
Display a linear combination
Ruby from D
Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots). Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is: :\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots where \alpha^{i_k}\neq 0 The output must comply to the following rules: * don't show null terms, unless the whole combination is null. ::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong. * don't show scalars when they are equal to one or minus one. ::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong. * don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. ::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
def linearCombo(c) sb = "" c.each_with_index { |n, i| if n == 0 then next end if n < 0 then if sb.length == 0 then op = "-" else op = " - " end elsif n > 0 then if sb.length > 0 then op = " + " else op = "" end else op = "" end av = n.abs() if av != 1 then coeff = "%d*" % [av] else coeff = "" end sb = sb + "%s%se(%d)" % [op, coeff, i + 1] } if sb.length == 0 then return "0" end return sb end def main combos = [ [1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, -3], [-1], ] for c in combos do print "%-15s -> %s\n" % [c, linearCombo(c)] end end main()
Distance and Bearing
Ruby
It is very important in aviation to have knowledge of the nearby airports at any time in flight. ;Task: Determine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested. Use the non-commercial data from openflights.org airports.dat as reference. A request comes from an airplane at position ( latitude, longitude ): ( '''51.514669, 2.198581''' ). Your report should contain the following information from table airports.dat (column shown in brackets): Name(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8). Distance is measured in nautical miles (NM). Resolution is 0.1 NM. Bearing is measured in degrees (deg). 0deg = 360deg = north then clockwise 90deg = east, 180deg = south, 270deg = west. Resolution is 1deg. ;See: :* openflights.org/data: Airport, airline and route data :* Movable Type Scripts: Calculate distance, bearing and more between Latitude/Longitude points
require 'open-uri' require 'csv' include Math RADIUS = 6372.8 # rough radius of the Earth, in kilometers def spherical_distance(start_coords, end_coords) lat1, long1 = deg2rad(*start_coords) lat2, long2 = deg2rad(*end_coords) 2 * RADIUS * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2)) end def bearing(start_coords, end_coords) lat1, long1 = deg2rad(*start_coords) lat2, long2 = deg2rad(*end_coords) dlon = long2 - long1 atan2(sin(dlon) * cos(lat2), cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)) end def deg2rad(lat, long) [lat * PI / 180, long * PI / 180] end uri = "https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat" headers = %i(airportID name city country iata icao latitude longitude altitude timezone dst tzOlson type source) data = CSV.parse(URI.open(uri), headers: headers, converters: :numeric) position = [51.514669, 2.198581] data.each{|r| r[:dist] = (spherical_distance(position, [r[:latitude], r[:longitude]])/1.852).round(1)} closest = data.min_by(20){|row| row[:dist] } closest.each do |r| bearing = (bearing(position,[r[:latitude], r[:longitude]])*180/PI).round % 360 puts "%-40s %-25s %-6s %12.1f %15.0f" % (r.values_at(:name, :country, :ICAO, :dist) << bearing) end
Diversity prediction theorem
Ruby from D
The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies. Scott E. Page introduced the diversity prediction theorem: : ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. Therefore, when the diversity in a group is large, the error of the crowd is small. ;Definitions: ::* Average Individual Error: Average of the individual squared errors ::* Collective Error: Squared error of the collective prediction ::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction ::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then :::::: Collective Error = Average Individual Error - Prediction Diversity ;Task: For a given true value and a number of number of estimates (from a crowd), show (here on this page): :::* the true value and the crowd estimates :::* the average error :::* the crowd error :::* the prediction diversity Use (at least) these two examples: :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51''' :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42''' ;Also see: :* Wikipedia entry: Wisdom of the crowd :* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
def mean(a) = a.sum(0.0) / a.size def mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 }) def diversity_theorem(truth, predictions) average = mean(predictions) puts "truth: #{truth}, predictions #{predictions}", "average-error: #{mean_square_diff(truth, predictions)}", "crowd-error: #{(truth - average)**2}", "diversity: #{mean_square_diff(average, predictions)}","" end diversity_theorem(49.0, [48.0, 47.0, 51.0]) diversity_theorem(49.0, [48.0, 47.0, 51.0, 42.0])
Dot product
Ruby
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
class Array def dot_product(other) raise "not the same size!" if self.length != other.length zip(other).sum {|a, b| a*b} end end p [1, 3, -5].dot_product [4, -2, -1] # => 3
Dutch national flag problem
Ruby
The Dutch national flag is composed of three coloured bands in the order: ::* red (top) ::* then white, and ::* lastly blue (at the bottom). The problem posed by Edsger Dijkstra is: :Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... ;Task # Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''. # Sort the balls in a way idiomatic to your language. # Check the sorted balls ''are'' in the order of the Dutch national flag. ;C.f.: * Dutch national flag problem * Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
class Ball FLAG = {red: 1, white: 2, blue: 3} def initialize @color = FLAG.keys.sample end def color @color end def <=>(other) # needed for sort, results in -1 for <, 0 for == and 1 for >. FLAG[self.color] <=> FLAG[other.color] end def inspect @color end end balls = [] balls = Array.new(8){Ball.new} while balls == balls.sort puts "Random: #{balls}" puts "Sorted: #{balls.sort}"
Eban numbers
Ruby from C#
Definition: An '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English. Or more literally, spelled numbers that contain the letter '''e''' are banned. The American version of spelling numbers will be used here (as opposed to the British). '''2,000,000,000''' is two billion, ''not'' two milliard. Only numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task. This will allow optimizations to be used. ;Task: :::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count :::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count :::* show a count of all eban numbers up and including '''10,000''' :::* show a count of all eban numbers up and including '''100,000''' :::* show a count of all eban numbers up and including '''1,000,000''' :::* show a count of all eban numbers up and including '''10,000,000''' :::* show all output here. ;See also: :* The MathWorld entry: eban numbers. :* The OEIS entry: A6933, eban numbers. :* [[Number names]].
def main intervals = [ [2, 1000, true], [1000, 4000, true], [2, 10000, false], [2, 100000, false], [2, 1000000, false], [2, 10000000, false], [2, 100000000, false], [2, 1000000000, false] ] for intv in intervals (start, ending, display) = intv if start == 2 then print "eban numbers up to and including %d:\n" % [ending] else print "eban numbers between %d and %d (inclusive):\n" % [start, ending] end count = 0 for i in (start .. ending).step(2) b = (i / 1000000000).floor r = (i % 1000000000) m = (r / 1000000).floor r = (r % 1000000) t = (r / 1000).floor r = (r % 1000) if m >= 30 and m <= 66 then m = m % 10 end if t >= 30 and t <= 66 then t = t % 10 end if r >= 30 and r <= 66 then r = r % 10 end if b == 0 or b == 2 or b == 4 or b == 6 then if m == 0 or m == 2 or m == 4 or m == 6 then if t == 0 or t == 2 or t == 4 or t == 6 then if r == 0 or r == 2 or r == 4 or r == 6 then if display then print ' ', i end count = count + 1 end end end end end if display then print "\n" end print "count = %d\n\n" % [count] end end main()
Eertree
Ruby from D
An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both ''tries'' and ''suffix trees''. See links below. ;Task: Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. ;See also: * Wikipedia entry: trie. * Wikipedia entry: suffix tree * Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
class Node def initialize(length, edges = {}, suffix = 0) @length = length @edges = edges @suffix = suffix end attr_reader :length attr_reader :edges attr_accessor :suffix end EVEN_ROOT = 0 ODD_ROOT = 1 def eertree(s) tree = [ Node.new(0, {}, ODD_ROOT), Node.new(-1, {}, ODD_ROOT) ] suffix = ODD_ROOT s.each_char.with_index { |c, i| n = suffix k = 0 loop do k = tree[n].length b = i - k - 1 if b >= 0 and s[b] == c then break end n = tree[n].suffix end if tree[n].edges.key?(c) then suffix = tree[n].edges[c] next end suffix = tree.length tree << Node.new(k + 2) tree[n].edges[c] = suffix if tree[suffix].length == 1 then tree[suffix].suffix = 0 next end loop do n = tree[n].suffix b = i - tree[n].length - 1 if b >= 0 and s[b] == c then break end end tree[suffix].suffix = tree[n].edges[c] } return tree end def subPalindromes(tree) s = [] children = lambda { |n,p,f| for c,v in tree[n].edges m = tree[n].edges[c] p = c + p + c s << p f.call(m, p, f) end } children.call(0, '', children) for c,n in tree[1].edges s << c children.call(n, c, children) end return s end tree = eertree("eertree") print subPalindromes(tree), "\n"
Egyptian division
Ruby
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
def egyptian_divmod(dividend, divisor) table = [[1, divisor]] table << table.last.map{|e| e*2} while table.last.first * 2 <= dividend answer, accumulator = 0, 0 table.reverse_each do |pow, double| if accumulator + double <= dividend accumulator += double answer += pow end end [answer, dividend - accumulator] end puts "Quotient = %s Remainder = %s" % egyptian_divmod(580, 34)
Elementary cellular automaton
Ruby
An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. ;Task: Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of [[one-dimensional cellular automata]]. ;See also * Cellular automata (natureofcode.com)
class ElemCellAutomat include Enumerable def initialize (start_str, rule, disp=false) @cur = start_str @patterns = Hash[8.times.map{|i|["%03b"%i, "01"[rule[i]]]}] puts "Rule (#{rule}) : #@patterns" if disp end def each return to_enum unless block_given? loop do yield @cur str = @cur[-1] + @cur + @cur[0] @cur = @cur.size.times.map {|i| @patterns[str[i,3]]}.join end end end eca = ElemCellAutomat.new('1'.center(39, "0"), 18, true) eca.take(30).each{|line| puts line.tr("01", ".#")}
Elementary cellular automaton/Infinite length
Ruby from Python
The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
def notcell(c) c.tr('01','10') end def eca_infinite(cells, rule) neighbours2next = Hash[8.times.map{|i|["%03b"%i, "01"[rule[i]]]}] c = cells Enumerator.new do |y| loop do y << c c = notcell(c[0])*2 + c + notcell(c[-1])*2 # Extend and pad the ends c = (1..c.size-2).map{|i| neighbours2next[c[i-1..i+1]]}.join end end end if __FILE__ == $0 lines = 25 for rule in [90, 30] puts "\nRule: %i" % rule for i, c in (0...lines).zip(eca_infinite('1', rule)) puts '%2i: %s%s' % [i, ' '*(lines - i), c.tr('01', '.#')] end end end
Elementary cellular automaton/Random number generator
Ruby
Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. ;Reference: * Cellular automata: Is Rule 30 random? (PDF).
size = 100 eca = ElemCellAutomat.new("1"+"0"*(size-1), 30) eca.take(80).map{|line| line[0]}.each_slice(8){|bin| p bin.join.to_i(2)}
Empty string
Ruby
Languages may have features for dealing specifically with empty strings (those containing no characters). ;Task: ::* Demonstrate how to assign an empty string to a variable. ::* Demonstrate how to check that a string is empty. ::* Demonstrate how to check that a string is not empty.
s == "" s.eql?("") s.empty? s.length == 0 s[/\A\z/] # also silly things like s.each_char.to_a.empty?
Entropy/Narcissist
Ruby
Write a computer program that computes and shows its own [[entropy]]. ;Related Tasks: :* [[Fibonacci_word]] :* [[Entropy]]
def entropy(s) counts = s.each_char.tally size = s.size.to_f counts.values.reduce(0) do |entropy, count| freq = count / size entropy - freq * Math.log2(freq) end end s = File.read(__FILE__) p entropy(s)
Equilibrium index
Ruby
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence A: ::::: A_0 = -7 ::::: A_1 = 1 ::::: A_2 = 5 ::::: A_3 = 2 ::::: A_4 = -4 ::::: A_5 = 3 ::::: A_6 = 0 3 is an equilibrium index, because: ::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6 6 is also an equilibrium index, because: ::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. ;Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
def eq_indices(list) result = [] list.empty? and return result final = list.size - 1 helper = lambda do |left, current, right, index| left == right and result << index # Push index to result? index == final and return # Terminate recursion? new = list[index + 1] helper.call(left + current, new, right - new, index + 1) end helper.call 0, list.first, list.drop(1).sum, 0 result end
Esthetic numbers
Ruby from Kotlin
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1. ;E.G. :* '''12''' is an esthetic number. One and two differ by 1. :* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour. :* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. ;Task :* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. :* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) :* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''. :* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''. ;Related task: * numbers with equal rises and falls ;See also: :;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 :;*Numbers Aplenty - Esthetic numbers :;*Geeks for Geeks - Stepping numbers
def isEsthetic(n, b) if n == 0 then return false end i = n % b n2 = (n / b).floor while n2 > 0 j = n2 % b if (i - j).abs != 1 then return false end n2 = n2 / b i = j end return true end def listEsths(n, n2, m, m2, perLine, all) esths = Array.new dfs = lambda {|n, m, i| if n <= i and i <= m then esths << i end if i == 0 or i > m then return end d = i % 10 i1 = i * 10 + d - 1 i2 = i1 + 2 if d == 0 then dfs[n, m, i2] elsif d == 9 then dfs[n, m, i1] else dfs[n, m, i1] dfs[n, m, i2] end } for i in 0..9 dfs[n2, m2, i] end le = esths.length print "Base 10: %d esthetic numbers between %d and %d:\n" % [le, n, m] if all then esths.each_with_index { |esth, idx| print "%d " % [esth] if (idx + 1) % perLine == 0 then print "\n" end } print "\n" else for i in 0 .. perLine - 1 print "%d " % [esths[i]] end print "\n............\n" for i in le - perLine .. le - 1 print "%d " % [esths[i]] end print "\n" end print "\n" end def main for b in 2..16 print "Base %d: %dth to %dth esthetic numbers:\n" % [b, 4 * b, 6 * b] n = 1 c = 0 while c < 6 * b if isEsthetic(n, b) then c = c + 1 if c >= 4 * b then print "%s " % [n.to_s(b)] end end n = n + 1 end print "\n" end print "\n" listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true) listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false) listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false) listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false) end main()
Euler's sum of powers conjecture
Ruby
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
power5 = (1..250).each_with_object({}){|i,h| h[i**5]=i} result = power5.keys.repeated_combination(4).select{|a| power5[a.inject(:+)]} puts result.map{|a| a.map{|i| "#{power5[i]}**5"}.join(' + ') + " = #{power5[a.inject(:+)]}**5"}
Euler's sum of powers conjecture
Ruby from Python
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
p5, sum2, max = {}, {}, 250 (1..max).each do |i| p5[i**5] = i (i..max).each{|j| sum2[i**5 + j**5] = [i,j]} end result = {} sk = sum2.keys.sort p5.keys.sort.each do |p| sk.each do |s| break if p <= s result[(sum2[s] + sum2[p-s]).sort] = p5[p] if sum2[p - s] end end result.each{|k,v| puts k.map{|i| "#{i}**5"}.join(' + ') + " = #{v}**5"}
Even or odd
Ruby
Test whether an integer is even or odd. There is more than one way to solve this task: * Use the even and odd predicates, if the language provides them. * Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd. * Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd. * Use modular congruences: ** ''i'' 0 (mod 2) iff ''i'' is even. ** ''i'' 1 (mod 2) iff ''i'' is odd.
print "evens: " p -5.upto(5).select(&:even?) print "odds: " p -5.upto(5).select(&:odd?)
Evolutionary algorithm
Ruby from C
Starting with: * The target string: "METHINKS IT IS LIKE A WEASEL". * An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). * A fitness function that computes the 'closeness' of its argument to the target string. * A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. :* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. :* repeat until the parent converges, (hopefully), to the target. ;See also: * Wikipedia entry: Weasel algorithm. * Wikipedia entry: Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, '''changing randomly any characters which don't already match the target''': ''NOTE:'' this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
@target = "METHINKS IT IS LIKE A WEASEL" Charset = [" ", *"A".."Z"] COPIES = 100 def random_char; Charset.sample end def fitness(candidate) sum = 0 candidate.chars.zip(@target.chars) {|x,y| sum += (x[0].ord - y[0].ord).abs} 100.0 * Math.exp(Float(sum) / -10.0) end def mutation_rate(candidate) 1.0 - Math.exp( -(100.0 - fitness(candidate)) / 400.0) end def mutate(parent, rate) parent.each_char.collect {|ch| rand <= rate ? random_char : ch}.join end def log(iteration, rate, parent) puts "%4d %.2f %5.1f %s" % [iteration, rate, fitness(parent), parent] end iteration = 0 parent = Array.new(@target.length) {random_char}.join prev = "" while parent != @target iteration += 1 rate = mutation_rate(parent) if prev != parent log(iteration, rate, parent) prev = parent end copies = [parent] + Array.new(COPIES) {mutate(parent, rate)} parent = copies.max_by {|c| fitness(c)} end log(iteration, rate, parent)
Executable library
Ruby
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. '''Task detail''' * Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number. * The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task: :: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 :: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. * Create a second executable to calculate the following: ** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000. * Explain any extra setup/run steps needed to complete the task. '''Notes:''' * It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment. * Interpreters are present in the runtime environment.
An executable library checks ''__FILE__ == $0''. Here, ''__FILE__'' is the path of the current source file, and ''$0'' is the path of the current executable. If ''__FILE__ == $0'', then the current source file is the executable, else the current source file is a library for some other executable. * ''__FILE__ == $0'' also works with older versions of Ruby, but this Hailstone example calls new methods in Ruby 1.8.7. This is ''hailstone.rb'', a modification of [[Hailstone sequence#Ruby]] as an executable library.
Executable library
Ruby 1.8.7
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. '''Task detail''' * Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number. * The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task: :: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 :: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. * Create a second executable to calculate the following: ** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000. * Explain any extra setup/run steps needed to complete the task. '''Notes:''' * It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment. * Interpreters are present in the runtime environment.
# hailstone.rb module Hailstone module_function def hailstone n seq = [n] until n == 1 n = (n.even?) ? (n / 2) : (3 * n + 1) seq << n end seq end end if __FILE__ == $0 include Hailstone # for n = 27, show sequence length and first and last 4 elements hs27 = hailstone 27 p [hs27.length, hs27[0..3], hs27[-4..-1]] # find the longest sequence among n less than 100,000 n, len = (1 ... 100_000) .collect {|n| [n, hailstone(n).length]} .max_by {|n, len| len} puts "#{n} has a hailstone sequence length of #{len}" puts "the largest number in that sequence is #{hailstone(n).max}" end
Exponentiation order
Ruby
This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents. (Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.) ;Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification): ::::* 5**3**2 ::::* (5**3)**2 ::::* 5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. ;See also: * MathWorld entry: exponentiation ;Related tasks: * exponentiation operator * arbitrary-precision integers (included) * [[Exponentiation with infix operators in (or operating on) the base]]
ar = ["5**3**2", "(5**3)**2", "5**(3**2)", "[5,3,2].inject(:**)"] ar.each{|exp| puts "#{exp}:\t#{eval exp}"}
Exponentiation with infix operators in (or operating on) the base
Ruby
(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation (raising numbers to some power by the language's exponentiation operator, if the computer programming language has one). Other programming languages may make use of the '''POW''' or some other BIF ('''B'''uilt-'''I'''n '''F'''function), or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an ''infix operator'' operating in (or operating on) the base. ;Example: A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). ;Task: :* compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred. :* Raise the following numbers (integer or real): :::* -5 and :::* +5 :* to the following powers: :::* 2nd and :::* 3rd :* using the following expressions (if applicable in your language): :::* -x**p :::* -(x)**p :::* (-x)**p :::* -(x**p) :* Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. ;Related tasks: * [[Exponentiation order]] * [[Exponentiation operator]] * [[Arbitrary-precision integers (included)]] * [[Parsing/RPN to infix conversion]] * [[Operator precedence]] ;References: * Wikipedia: Order of operations in Programming languages
nums = [-5, 5] pows = [2, 3] nums.product(pows) do |x, p| puts "x = #{x} p = #{p}\t-x**p #{-x**p}\t-(x)**p #{-(x)**p}\t(-x)**p #{ (-x)**p}\t-(x**p) #{-(x**p)}" end
Extend your language
Ruby
{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
# Define a class which always returns itself for everything class HopelesslyEgocentric def method_missing(what, *args) self end end def if2(cond1, cond2) if cond1 and cond2 yield HopelesslyEgocentric.new elsif cond1 Class.new(HopelesslyEgocentric) do def else1; yield; HopelesslyEgocentric.new end end.new elsif cond2 Class.new(HopelesslyEgocentric) do def else2; yield; HopelesslyEgocentric.new end end.new else Class.new(HopelesslyEgocentric) do def neither; yield end end.new end end
Extreme floating point values
Ruby
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. ;See also: * What Every Computer Scientist Should Know About Floating-Point Arithmetic ;Related tasks: * [[Infinity]] * [[Detect division by zero]] * [[Literals/Floating point]]
inf = 1.0 / 0.0 # or Float::INFINITY nan = 0.0 / 0.0 # or Float::NAN expression = [ "1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0", "inf + 1", "5 - inf", "inf * 5", "inf / 5", "inf * 0", "1.0 / inf", "-1.0 / inf", "inf + inf", "inf - inf", "inf * inf", "inf / inf", "inf * 0.0", " 0 < inf", "inf == inf", "nan + 1", "nan * 5", "nan - nan", "nan * inf", "- nan", "nan == nan", "nan > 0", "nan < 0", "nan == 0", "nan <=> 0.0", "0.0 == -0.0", ] expression.each do |exp| puts "%15s => %p" % [exp, eval(exp)] end
FASTA format
Ruby
In FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. ;Task: Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED
def fasta_format(strings) out, text = [], "" strings.split("\n").each do |line| if line[0] == '>' out << text unless text.empty? text = line[1..-1] + ": " else text << line end end out << text unless text.empty? end data = <<'EOS' >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED EOS puts fasta_format(data)
Factorial primes
Ruby
Definition A factorial. In other words a non-negative integer '''n''' corresponds to a factorial prime if either '''n'''! - 1 or '''n'''! + 1 is prime. ;Examples 4 corresponds to the factorial prime 4! - 1 = 23. 5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime. ;Task Find and show here the first 10 factorial primes. As well as the prime itself show the factorial number '''n''' to which it corresponds and whether 1 is to be added or subtracted. As 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!. ;Stretch If your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes. As it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function. If a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has. ;Reference * OEIS:A088054 - Factorial primes ;Related task * Sequence of primorial primes
require 'openssl' factorial_primes = Enumerator.new do |y| fact = 1 (1..).each do |i| fact *= i y << [i, "- 1", fact - 1] if OpenSSL::BN.new(fact - 1).prime? y << [i, "+ 1", fact + 1] if OpenSSL::BN.new(fact + 1).prime? end end factorial_primes.first(30).each do |a| s = a.last.to_s if s.size > 40 then puts "%d! %s = " % a.first(2) + "#{s[0,20]}...#{s[-20,20]}" else puts "%d! %s = %d" % a end end
Factorions
Ruby
Definition: A factorion is a natural number that equals the sum of the factorials of its digits. ;Example: '''145''' is a factorion in base '''10''' because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''. ;Task: Write a program in your language to demonstrate, by calculating and printing out the factorions, that: :* There are '''3''' factorions in base '''9''' :* There are '''4''' factorions in base '''10''' :* There are '''5''' factorions in base '''11''' :* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''') ;See also: :* '''Wikipedia article''' :* '''OEIS:A014080 - Factorions in base 10''' :* '''OEIS:A193163 - Factorions in base n'''
def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n end (9..12).each do |base| puts "Base #{base} factorions: #{(1..1_500_000).select{|n| factorion?(n, base)}.join(" ")} " end
Fairshare between two and more
Ruby from C
The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: :''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"'' ;Sharing fairly between two or more: Use this method: :''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.'' ;Task Counting from zero; using a function/method/routine to express an integer count in base '''b''', sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people. Show the first 25 terms of the fairshare sequence: :* For two people: :* For three people :* For five people :* For eleven people ;Related tasks: :* [[Non-decimal radices/Convert]] :* [[Thue-Morse]] ;See also: :* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
def turn(base, n) sum = 0 while n != 0 do rem = n % base n = n / base sum = sum + rem end return sum % base end def fairshare(base, count) print "Base %2d: " % [base] for i in 0 .. count - 1 do t = turn(base, i) print " %2d" % [t] end print "\n" end def turnCount(base, count) cnt = Array.new(base, 0) for i in 0 .. count - 1 do t = turn(base, i) cnt[t] = cnt[t] + 1 end minTurn = base * count maxTurn = -1 portion = 0 for i in 0 .. base - 1 do if cnt[i] > 0 then portion = portion + 1 end if cnt[i] < minTurn then minTurn = cnt[i] end if cnt[i] > maxTurn then maxTurn = cnt[i] end end print " With %d people: " % [base] if 0 == minTurn then print "Only %d have a turn\n" % portion elsif minTurn == maxTurn then print "%d\n" % [minTurn] else print "%d or %d\n" % [minTurn, maxTurn] end end def main fairshare(2, 25) fairshare(3, 25) fairshare(5, 25) fairshare(11, 25) puts "How many times does each get a turn in 50000 iterations?" turnCount(191, 50000) turnCount(1377, 50000) turnCount(49999, 50000) turnCount(50000, 50000) turnCount(50001, 50000) end main()
Fairshare between two and more
Ruby from Sidef
The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: :''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"'' ;Sharing fairly between two or more: Use this method: :''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.'' ;Task Counting from zero; using a function/method/routine to express an integer count in base '''b''', sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people. Show the first 25 terms of the fairshare sequence: :* For two people: :* For three people :* For five people :* For eleven people ;Related tasks: :* [[Non-decimal radices/Convert]] :* [[Thue-Morse]] ;See also: :* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
def fairshare(base, upto) = (0...upto).map{|n| n.digits(base).sum % base} upto = 25 [2, 3, 5, 11].each{|b| puts"#{'%2d' % b}: " + " %2d"*upto % fairshare(b, upto)}
Farey sequence
Ruby from Python
The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size. The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. Each Farey sequence: :::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1} :::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}. The Farey sequences of orders '''1''' to '''5''' are: :::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1} : :::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1} : :::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1} : :::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1} : :::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1} ;Task * Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive). * Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds. * Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). The length (the number of fractions) of a Farey sequence asymptotically approaches: ::::::::::: 3 x n2 / \pi2 ;See also: * OEIS sequence A006842 numerators of Farey series of order 1, 2, *** * OEIS sequence A006843 denominators of Farey series of order 1, 2, *** * OEIS sequence A005728 number of fractions in Farey series of order n * MathWorld entry Farey sequence * Wikipedia entry Farey sequence
def farey(n, length=false) if length (n*(n+3))/2 - (2..n).sum{|k| farey(n/k, true)} else (1..n).each_with_object([]){|k,a|(0..k).each{|m|a << Rational(m,k)}}.uniq.sort end end puts 'Farey sequence for order 1 through 11 (inclusive):' for n in 1..11 puts "F(#{n}): " + farey(n).join(", ") end puts 'Number of fractions in the Farey sequence:' for i in (100..1000).step(100) puts "F(%4d) =%7d" % [i, farey(i, true)] end
Fast Fourier transform
Ruby
Calculate the FFT (Fast Fourier Transform) of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
def fft(vec) return vec if vec.size <= 1 evens_odds = vec.partition.with_index{|_,i| i.even?} evens, odds = evens_odds.map{|even_odd| fft(even_odd)*2} evens.zip(odds).map.with_index do |(even, odd),i| even + odd * Math::E ** Complex(0, -2 * Math::PI * i / vec.size) end end fft([1,1,1,1,0,0,0,0]).each{|c| puts "%9.6f %+9.6fi" % c.rect}
Feigenbaum constant calculation
Ruby from C#
Calculate the Feigenbaum constant. ;See: :* Details in the Wikipedia article: Feigenbaum constant.
def main maxIt = 13 maxItJ = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 puts " i d" for i in 2 .. maxIt a = a1 + (a1 - a2) / d1 for j in 1 .. maxItJ x = 0.0 y = 0.0 for k in 1 .. 1 << i y = 1.0 - 2.0 * y * x x = a - x * x end a = a - x / y end d = (a1 - a2) / (a - a1) print "%2d %.8f\n" % [i, d] d1 = d a2 = a1 a1 = a end end main()
Fibonacci n-step number sequences
Ruby
These number series are an expansion of the ordinary [[Fibonacci sequence]] where: # For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2 # For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3 # For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4... # For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}} For small values of n, Greek numeric prefixes are sometimes used to individually name each series. :::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2" |+ Fibonacci n-step sequences |- style="background-color: rgb(255, 204, 255);" ! n !! Series name !! Values |- | 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |- | 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |- | 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |- | 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |- | 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |- | 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |- | 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |- | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |- | 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |} Allied sequences can be generated where the initial values are changed: : '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values. ;Task: # Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. # Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. ;Related tasks: * [[Fibonacci sequence]] * Wolfram Mathworld * [[Hofstadter Q sequence]] * [[Leonardo numbers]] ;Also see: * Lucas Numbers - Numberphile (Video) * Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video) * Wikipedia, Lucas number * MathWorld, Fibonacci Number * Some identities for r-Fibonacci numbers * OEIS Fibonacci numbers * OEIS Lucas numbers
def anynacci(start_sequence, count) n = start_sequence.length # Get the n-step for the type of fibonacci sequence result = start_sequence.dup # Create a new result array with the values copied from the array that was passed by reference (count-n).times do # Loop for the remaining results up to count result << result.last(n).sum # Get the last n element from result and append its total to Array end result end naccis = { lucas: [2,1], fibonacci: [1,1], tribonacci: [1,1,2], tetranacci: [1,1,2,4], pentanacci: [1,1,2,4,8], hexanacci: [1,1,2,4,8,16], heptanacci: [1,1,2,4,8,16,32], octonacci: [1,1,2,4,8,16,32,64], nonanacci: [1,1,2,4,8,16,32,64,128], decanacci: [1,1,2,4,8,16,32,64,128,256] } naccis.each {|name, seq| puts "%12s : %p" % [name, anynacci(seq, 15)]}
Fibonacci word
Ruby
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here: Define F_Word1 as '''1''' Define F_Word2 as '''0''' Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01''' Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2 ;Task: Perform the above steps for n = 37. You may display the first few but not the larger values of n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for F_Words '''1''' to '''37''' which shows: ::* The number of characters in the word ::* The word's [[Entropy]] ;Related tasks: * Fibonacci word/fractal * [[Entropy]] * [[Entropy/Narcissist]]
#encoding: ASCII-8BIT def entropy(s) counts = Hash.new(0.0) s.each_char { |c| counts[c] += 1 } leng = s.length counts.values.reduce(0) do |entropy, count| freq = count / leng entropy - freq * Math.log2(freq) end end n_max = 37 words = ['1', '0'] for n in words.length ... n_max words << words[-1] + words[-2] end puts '%3s %9s %15s %s' % %w[N Length Entropy Fibword] words.each.with_index(1) do |word, i| puts '%3i %9i %15.12f %s' % [i, word.length, entropy(word), word.length<60 ? word : '<too long>'] end
File extension is in extensions list
Ruby
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''. It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid. For these reasons, this task exists in addition to the [[Extract file extension]] task. ;Related tasks: * [[Extract file extension]] * [[String matching]]
def is_ext(filename, extensions) if filename.respond_to?(:each) filename.each do |fn| is_ext(fn, extensions) end else fndc = filename.downcase extensions.each do |ext| bool = fndc.end_with?(?. + ext.downcase) puts "%20s : %s" % [filename, bool] if bool end end end
Find Chess960 starting position identifier
Ruby
Starting Position Identifier number ("SP-ID"), and generate the corresponding position. ;Task: This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array '''QNRBBNKR''' (or '''''' or ''''''), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518. You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional. ;Algorithm: The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example). 1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0='''NN---''', 1='''N-N--''', 2='''N--N-''', 3='''N---N''', 4='''-NN--''', etc; our pair is combination number 5. Call this number N. '''N=5''' 2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, '''Q=2'''. 3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 ('''D=1'''), and the light bishop is on square 2 ('''L=2'''). 4. Then the position number is given by '''4(4(6N + Q)+D)+L''', which reduces to '''96N + 16Q + 4D + L'''. In our example, that's 96x5 + 16x2 + 4x1 + 2 = 480 + 32 + 4 + 2 = 518. Note that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions. RQNBBKRN = 601 RNQBBKRN = 617
CHESS_PIECES = %w<β™–β™˜β™—β™•β™” β™œβ™žβ™β™›β™š> def chess960_to_spid(pos) start_str = pos.tr(CHESS_PIECES.join, "RNBQKRNBQK") #1 knights score s = start_str.delete("QB") n = [0,1,2,3,4].combination(2).to_a.index( [s.index("N"), s.rindex("N")] ) #2 queen score q = start_str.delete("B").index("Q") #3 bishops bs = start_str.index("B"), start_str.rindex("B") d = bs.detect(&:even?).div(2) l = bs.detect(&:odd? ).div(2) 96*n + 16*q + 4*d + l end %w<QNRBBNKR RNBQKBNR RQNBBKRN RNQBBKRN>.each_with_index do |array, i| pieces = array.tr("RNBQK", CHESS_PIECES[i%2]) puts "#{pieces} (#{array}): #{chess960_to_spid array}" end
Find duplicate files
Ruby
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. ;Task: Create a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size. The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data. Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements. Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem. For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
require 'digest/md5' def find_duplicate_files(dir) puts "\nDirectory : #{dir}" Dir.chdir(dir) do file_size = Dir.foreach('.').select{|f| FileTest.file?(f)}.group_by{|f| File.size(f)} file_size.each do |size, files| next if files.size==1 files.group_by{|f| Digest::MD5.file(f).to_s}.each do |md5,fs| next if fs.size==1 puts " --------------------------------------------" fs.each{|file| puts " #{File.mtime(file)} #{size} #{file}"} end end end end find_duplicate_files("/Windows/System32")
Find if a point is within a triangle
Ruby from Go
Find if a point is within a triangle. ;Task: ::* Assume points are on a plane defined by (x, y) real number coordinates. ::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. ::* You may use any algorithm. ::* Bonus: explain why the algorithm you chose works. ;Related tasks: * [[Determine_if_two_triangles_overlap]] ;Also see: :* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]] :* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]] :* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]] :* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]
EPS = 0.001 EPS_SQUARE = EPS * EPS def side(x1, y1, x2, y2, x, y) return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1) end def naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) checkSide1 = side(x1, y1, x2, y2, x, y) >= 0 checkSide2 = side(x2, y2, x3, y3, x, y) >= 0 checkSide3 = side(x3, y3, x1, y1, x, y) >= 0 return checkSide1 && checkSide2 && checkSide3 end def pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) xMin = [x1, x2, x3].min - EPS xMax = [x1, x2, x3].max + EPS yMin = [y1, y2, y3].min - EPS yMax = [y1, y2, y3].max + EPS return !(x < xMin || xMax < x || y < yMin || yMax < y) end def distanceSquarePointToSegment(x1, y1, x2, y2, x, y) p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength if dotProduct < 0 then return (x - x1) * (x - x1) + (y - y1) * (y - y1) end if dotProduct <= 1 then p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y) return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength end return (x - x2) * (x - x2) + (y - y2) * (y - y2) end def accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) then return false end if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) then return true end if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then return true end return false end def main pts = [[0, 0], [0, 1], [3, 1]] tri = [[1.5, 2.4], [5.1, -3.1], [-3.8, 1.2]] print "Triangle is ", tri, "\n" x1, y1 = tri[0][0], tri[0][1] x2, y2 = tri[1][0], tri[1][1] x3, y3 = tri[2][0], tri[2][1] for pt in pts x, y = pt[0], pt[1] within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) print "Point ", pt, " is within triangle? ", within, "\n" end print "\n" tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [25.0, 100.0 / 9.0]] print "Triangle is ", tri, "\n" x1, y1 = tri[0][0], tri[0][1] x2, y2 = tri[1][0], tri[1][1] x3, y3 = tri[2][0], tri[2][1] x = x1 + (3.0 / 7.0) * (x2 - x1) y = y1 + (3.0 / 7.0) * (y2 - y1) pt = [x, y] within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) print "Point ", pt, " is within triangle? ", within, "\n" print "\n" tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [-12.5, 100.0 / 6.0]] print "Triangle is ", tri, "\n" x3, y3 = tri[2][0], tri[2][1] within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) print "Point ", pt, " is within triangle? ", within, "\n" end main()
Find palindromic numbers in both binary and ternary bases
Ruby
* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'': :::* base 2 :::* base 3 * Display '''0''' (zero) as the first number found, even though some other definitions ignore it. * Optionally, show the decimal number found in its binary and ternary form. * Show all output here. It's permissible to assume the first two numbers and simply list them. ;See also * Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
pal23 = Enumerator.new do |y| y << 0 y << 1 for i in 1 .. 1.0/0.0 # 1.step do |i| (Ruby 2.1+) n3 = i.to_s(3) n = (n3 + "1" + n3.reverse).to_i(3) n2 = n.to_s(2) y << n if n2.size.odd? and n2 == n2.reverse end end puts " decimal ternary binary" 6.times do |i| n = pal23.next puts "%2d: %12d %s %s" % [i, n, n.to_s(3).center(25), n.to_s(2).center(39)] end
Find the intersection of a line with a plane
Ruby from C#
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. ;Task: Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
require "matrix" def intersectPoint(rayVector, rayPoint, planeNormal, planePoint) diff = rayPoint - planePoint prod1 = diff.dot planeNormal prod2 = rayVector.dot planeNormal prod3 = prod1 / prod2 return rayPoint - rayVector * prod3 end def main rv = Vector[0.0, -1.0, -1.0] rp = Vector[0.0, 0.0, 10.0] pn = Vector[0.0, 0.0, 1.0] pp = Vector[0.0, 0.0, 5.0] ip = intersectPoint(rv, rp, pn, pp) puts "The ray intersects the plane at %s" % [ip] end main()
Find the intersection of two lines
Ruby
Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html] ;Task: Find the point of intersection of two lines in 2D. The 1st line passes though (4,0) and (6,10) . The 2nd line passes though (0,3) and (10,7) .
Point = Struct.new(:x, :y) class Line attr_reader :a, :b def initialize(point1, point2) @a = (point1.y - point2.y).fdiv(point1.x - point2.x) @b = point1.y - @a*point1.x end def intersect(other) return nil if @a == other.a x = (other.b - @b).fdiv(@a - other.a) y = @a*x + @b Point.new(x,y) end def to_s "y = #{@a}x #{@b.positive? ? '+' : '-'} #{@b.abs}" end end l1 = Line.new(Point.new(4, 0), Point.new(6, 10)) l2 = Line.new(Point.new(0, 3), Point.new(10, 7)) puts "Line #{l1} intersects line #{l2} at #{l1.intersect(l2)}."
Find the last Sunday of each month
Ruby
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 ;Related tasks * [[Day of the week]] * [[Five weekends]] * [[Last Friday of each month]]
require 'date' def last_sundays_of_year(year = Date.today.year) (1..12).map do |month| d = Date.new(year, month, -1) # -1 means "last". d - d.wday end end puts last_sundays_of_year(2013)
Find the missing permutation
Ruby 2.0+
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. ;Task: Find that missing permutation. ;Methods: * Obvious method: enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', and then look for the missing permutation. * alternate method: Hint: if all permutations were shown above, how many times would '''A''' appear in each position? What is the ''parity'' of this number? * another alternate method: Hint: if you add up the letter values of each column, does a missing letter '''A''', '''B''', '''C''', and '''D''' from each column cause the total value for each column to be unique? ;Related task: * [[Permutations]])
given = %w{ ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB } all = given[0].chars.permutation.collect(&:join) puts "missing: #{all - given}"
First-class functions/Use numbers analogously
Ruby
In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. '''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
multiplier = proc {|n1, n2| proc {|m| n1 * n2 * m}} numlist = [x=2, y=4, x+y] invlist = [0.5, 0.25, 1.0/(x+y)] p numlist.zip(invlist).map {|n, invn| multiplier[invn, n][0.5]} # => [0.5, 0.5, 0.5]
First perfect square in base n with n unique digits
Ruby
Find the first perfect square in a given base '''N''' that has at least '''N''' digits and exactly '''N''' ''significant unique'' digits when expressed in base '''N'''. E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432'''). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. ;Task * Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated. * (optional) Do the same for bases '''13''' through '''16'''. * (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math) ;See also: ;* OEIS A260182: smallest square that is pandigital in base n. ;Related task ;* [[Casting out nines]]
DIGITS = "1023456789abcdefghijklmnopqrstuvwxyz" 2.upto(16) do |n| start = Integer.sqrt( DIGITS[0,n].to_i(n) ) res = start.step.detect{|i| (i*i).digits(n).uniq.size == n } puts "Base %2d:%10sΒ² = %-14s" % [n, res.to_s(n), (res*res).to_s(n)] end
First power of 2 that has leading decimal digits of 12
Ruby from C
(This task is taken from a ''Project Euler'' problem.) (All numbers herein are expressed in base ten.) '''27 = 128''' and '''7''' is the first power of '''2''' whose leading decimal digits are '''12'''. The next power of '''2''' whose leading decimal digits are '''12''' is '''80''', '''280 = 1208925819614629174706176'''. Define ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest value of ''' ''j'' ''' such that the base ten representation of '''2''j''''' begins with the digits of ''' ''L'' '''. So ''p''(12, 1) = 7 and ''p''(12, 2) = 80 You are also given that: ''p''(123, 45) = 12710 ;Task: ::* find: :::::* ''' ''p''(12, 1) ''' :::::* ''' ''p''(12, 2) ''' :::::* ''' ''p''(123, 45) ''' :::::* ''' ''p''(123, 12345) ''' :::::* ''' ''p''(123, 678910) ''' ::* display the results here, on this page.
def p(l, n) test = 0 logv = Math.log(2.0) / Math.log(10.0) factor = 1 loopv = l while loopv > 10 do factor = factor * 10 loopv = loopv / 10 end while n > 0 do test = test + 1 val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor if val == l then n = n - 1 end end return test end def runTest(l, n) print "P(%d, %d) = %d\n" % [l, n, p(l, n)] end runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910)
Fivenum
Ruby from Perl
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory. For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function. ;Task: Given an array of numbers, compute the five-number summary. ;Note: While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
def fivenum(array) sorted_arr = array.sort n = array.size n4 = (((n + 3).to_f / 2.to_f) / 2.to_f).floor d = Array.[](1, n4, ((n.to_f + 1) / 2).to_i, n + 1 - n4, n) sum_array = [] (0..4).each do |e| # each loops have local scope, for loops don't index_floor = (d[e] - 1).floor index_ceil = (d[e] - 1).ceil sum_array.push(0.5 * (sorted_arr[index_floor] + sorted_arr[index_ceil])) end sum_array end test_array = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43] tukey_array = fivenum(test_array) p tukey_array test_array = [36, 40, 7, 39, 41, 15] tukey_array = fivenum(test_array) p tukey_array test_array = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578] tukey_array = fivenum(test_array) p tukey_array
Fixed length records
Ruby
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column. These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems). ;Task: Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat. '''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed. These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''. ;Sample data: To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size. Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input. prompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines. ;Bonus round: Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line). Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output. Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character. The COBOL example uses forth.txt and forth.blk filenames.
open("outfile.dat", "w") do |out_f| open("infile.dat") do |in_f| while record = in_f.read(80) out_f << record.reverse end end end # both files automatically closed
Flatten a list
Ruby
Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] ;Related task: * [[Tree traversal]]
p flatten_once = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten(1) # => [1, 2, [3, 4], 5, [[]], [[6]], 7, 8]
Flipping bits game
Ruby
The game: Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once (as one move). In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column. ;Task: Create a program to score for the Flipping bits game. # The game should create an original random target configuration and a starting configuration. # Ensure that the starting position is ''never'' the target position. # The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position). # The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a '''3x3''' array of bits.
class FlipBoard def initialize(size) raise ArgumentError.new("Invalid board size: #{size}") if size < 2 @size = size @board = Array.new(size**2, 0) randomize_board loop do @target = generate_target break unless solved? end # these are used for validating user input @columns = [*'a'...('a'.ord+@size).chr] @rows = (1..@size).map(&:to_s) end ############################################################ def play moves = 0 puts "your target:", target until solved? puts "", "move #{moves}:", self print "Row/column to flip: " ans = $stdin.gets.strip if @columns.include? ans flip_column @columns.index(ans) moves += 1 elsif @rows.include? ans flip_row @rows.index(ans) moves += 1 else puts "invalid input: " + ans end end puts "", "you solved the game in #{moves} moves", self end # the target formation as a string def target format_array @target end # the current formation as a string def to_s format_array @board end ############################################################ private def solved? @board == @target end # flip a random number of bits on the board def randomize_board (@size + rand(@size)).times do flip_bit rand(@size), rand(@size) end end # generate a random number of flip_row/flip_column calls def generate_target orig_board = @board.clone (@size + rand(@size)).times do rand(2).zero? ? flip_row( rand(@size) ) : flip_column( rand(@size) ) end target, @board = @board, orig_board target end def flip_row(row) @size.times {|col| flip_bit(row, col)} end def flip_column(col) @size.times {|row| flip_bit(row, col)} end def flip_bit(row, col) @board[@size * row + col] ^= 1 end def format_array(ary) str = " " + @columns.join(" ") + "\n" @size.times do |row| str << "%2s " % @rows[row] + ary[@size*row, @size].join(" ") + "\n" end str end end ###################################################################### begin FlipBoard.new(ARGV.shift.to_i).play rescue => e puts e.message end
Floyd's triangle
Ruby
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where * the first row is '''1''' (unity) * successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ;Task: :# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows). :# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
def floyd(rows) max = (rows * (rows + 1)) / 2 widths = ((max - rows + 1)..max).map {|n| n.to_s.length + 1} n = 0 rows.times do |r| puts (0..r).map {|i| n += 1; "%#{widths[i]}d" % n}.join end end floyd(5) floyd(14)
Four bit adder
Ruby
"''Simulate''" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two gate. ; Finally a half adder can be made using an ''xor'' gate and an ''and'' gate. The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''. '''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones. {| |+Schematics of the "constructive blocks" !(Xor gate with ANDs, ORs and NOTs) ! (A half adder) ! (A full adder) ! (A 4-bit adder) |- |Xor gate done with ands, ors and nots |A half adder |A full adder |A 4-bit adder |} Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
# returns pair [sum, carry] def four_bit_adder(a, b) a_bits = binary_string_to_bits(a,4) b_bits = binary_string_to_bits(b,4) s0, c0 = full_adder(a_bits[0], b_bits[0], 0) s1, c1 = full_adder(a_bits[1], b_bits[1], c0) s2, c2 = full_adder(a_bits[2], b_bits[2], c1) s3, c3 = full_adder(a_bits[3], b_bits[3], c2) [bits_to_binary_string([s0, s1, s2, s3]), c3.to_s] end # returns pair [sum, carry] def full_adder(a, b, c0) s, c = half_adder(c0, a) s, c1 = half_adder(s, b) [s, _or(c,c1)] end # returns pair [sum, carry] def half_adder(a, b) [xor(a, b), _and(a,b)] end def xor(a, b) _or(_and(a, _not(b)), _and(_not(a), b)) end # "and", "or" and "not" are Ruby keywords def _and(a, b) a & b end def _or(a, b) a | b end def _not(a) ~a & 1 end def int_to_binary_string(n, length) "%0#{length}b" % n end def binary_string_to_bits(s, length) ("%#{length}s" % s).reverse.chars.map(&:to_i) end def bits_to_binary_string(bits) bits.map(&:to_s).reverse.join end puts " A B A B C S sum" 0.upto(15) do |a| 0.upto(15) do |b| bin_a = int_to_binary_string(a, 4) bin_b = int_to_binary_string(b, 4) sum, carry = four_bit_adder(bin_a, bin_b) puts "%2d + %2d = %s + %s = %s %s = %2d" % [a, b, bin_a, bin_b, carry, sum, (carry + sum).to_i(2)] end end
Four is magic
Ruby
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' '''Three is five, five is four, four is magic.''' For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. ;Some task guidelines: :* You may assume the input will only contain integer numbers. :* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.) :* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) :* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.) :* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''. :* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''. :* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''. :* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") :* The output can either be the return value from the function, or be displayed from within the function. :* You are encouraged, though not mandated to use proper sentence capitalization. :* You may optionally support negative numbers. '''-7''' is '''negative seven'''. :* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code. ;Related tasks: :* [[Four is the number of_letters in the ...]] :* [[Look-and-say sequence]] :* [[Number names]] :* [[Self-describing numbers]] :* [[Summarize and say sequence]] :* [[Spelling of ordinal numbers]] :* [[De Bruijn sequences]]
module NumberToWord NUMBERS = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 40 => 'forty', 50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty', 90 => 'ninety', 100 => 'hundred', 1000 => 'thousand', 10 ** 6 => 'million', 10 ** 9 => 'billion', 10 ** 12 => 'trillion', 10 ** 15 => 'quadrillion', 10 ** 18 => 'quintillion', 10 ** 21 => 'sextillion', 10 ** 24 => 'septillion', 10 ** 27 => 'octillion', 10 ** 30 => 'nonillion', 10 ** 33 => 'decillion'}.reverse_each.to_h refine Integer do def to_english return 'zero' if i.zero? words = self < 0 ? ['negative'] : [] i = self.abs NUMBERS.each do |k, v| if k <= i then times = i/k words << times.to_english if k >= 100 words << v i -= times * k end return words.join(" ") if i.zero? end end end end using NumberToWord def magic4(n) words = [] until n == 4 s = n.to_english n = s.size words << "#{s} is #{n.to_english}" end words << "four is magic." words.join(", ").capitalize end [0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each{|n| puts magic4(n) }
Fusc sequence
Ruby
Definitions: The '''fusc''' integer sequence is defined as: ::* fusc(0) = 0 ::* fusc(1) = 1 ::* for '''n'''>1, the '''n'''th term is defined as: ::::* if '''n''' is even; fusc(n) = fusc(n/2) ::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above). ;An observation: :::::* fusc(A) = fusc(B) where '''A''' is some non-negative integer expressed in binary, and where '''B''' is the binary value of '''A''' reversed. Fusc numbers are also known as: ::* fusc function (named by Dijkstra, 1982) ::* Stern's Diatomic series (although it starts with unity, not zero) ::* Stern-Brocot sequence (although it starts with unity, not zero) ;Task: ::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format. ::* show the fusc number (and its index) whose length is greater than any previous fusc number length. ::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.) ::* show all numbers with commas (if appropriate). ::* show all output here. ;Related task: ::* RosettaCode Stern-Brocot sequence ;Also see: ::* the MathWorld entry: Stern's Diatomic Series. ::* the OEIS entry: A2487.
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp += 1 cur_max = 10**cur_exp y << [i, f] end end end puts fusc.take(61).join(" ") fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
Gapful numbers
Ruby
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: '''187''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''187'''. About 7.46% of positive integers are ''gapful''. ;Task: :* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page :* Show the first '''30''' gapful numbers :* Show the first '''15''' gapful numbers >= '''1,000,000''' :* Show the first '''10''' gapful numbers >= '''1,000,000,000''' ;Related tasks: :* Harshad or Niven series. :* palindromic gapful numbers. :* largest number divisible by its digits. ;Also see: :* The OEIS entry: A108343 gapful numbers. :* numbersaplenty gapful numbers
class Integer def gapful? a = digits self % (a.last*10 + a.first) == 0 end end specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25} specs.each do |start, num| puts "first #{num} gapful numbers >= #{start}:" p (start..).lazy.select(&:gapful?).take(num).to_a end
Gauss-Jordan matrix inversion
Ruby
Invert matrix '''A''' using Gauss-Jordan method. '''A''' being an '''n''' x '''n''' matrix.
require 'matrix' m = Matrix[[-1, -2, 3, 2], [-4, -1, 6, 2], [ 7, -8, 9, 1], [ 1, -2, 1, 3]] pp m.inv.row_vectors
Gaussian elimination
Ruby
Solve '''Ax=b''' using Gaussian elimination then backwards substitution. '''A''' being an '''n''' by '''n''' matrix. Also, '''x''' and '''b''' are '''n''' by '''1''' vectors. To improve accuracy, please use partial pivoting and scaling. ;See also: :* the Wikipedia entry: Gaussian elimination
require 'bigdecimal/ludcmp' include LUSolve BigDecimal::limit(30) a = [1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02].map{|i|BigDecimal(i,16)} b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02].map{|i|BigDecimal(i,16)} n = 6 zero = BigDecimal("0.0") one = BigDecimal("1.0") lusolve(a, b, ludecomp(a, n, zero,one), zero).each{|v| puts v.to_s('F')[0..20]}
Generate Chess960 starting position
Ruby
Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: ** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) ** the King must be between two rooks (with any number of other pieces between them all) * Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are '''960''' possible starting positions, thus the name of the variant. ;Task: The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.
pieces = %i(β™” β™• β™˜ β™˜ β™— β™— β™– β™–) regexes = [/β™—(..)*β™—/, /β™–.*β™”.*β™–/] row = pieces.shuffle.join until regexes.all?{|re| re.match(row)} puts row
Generate random chess position
Ruby
Generate a random chess position in FEN format. The position does not have to be realistic or even balanced, but it must comply to the following rules: :* there is one and only one king of each color (one black king and one white king); :* the kings must not be placed on adjacent squares; :* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank); :* including the kings, up to 32 pieces of either color can be placed. :* There is no requirement for material balance between sides. :* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. :* it is white's turn. :* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
def hasNK( board, a, b ) for g in -1 .. 1 for f in -1 .. 1 aa = a + f; bb = b + g if aa.between?( 0, 7 ) && bb.between?( 0, 7 ) p = board[aa + 8 * bb] if p == "K" || p == "k"; return true; end end end end return false end def generateBoard( board, pieces ) while( pieces.length > 1 ) p = pieces[pieces.length - 1] pieces = pieces[0...-1] while( true ) a = rand( 8 ); b = rand( 8 ) if ( ( b == 0 || b == 7 ) && ( p == "P" || p == "p" ) ) || ( ( p == "k" || p == "K" ) && hasNK( board, a, b ) ); next; end if board[a + b * 8] == nil; break;end end board[a + b * 8] = p end end pieces = "ppppppppkqrrbbnnPPPPPPPPKQRRBBNN" for i in 0 .. 10 e = pieces.length - 1 while e > 0 p = rand( e ); t = pieces[e]; pieces[e] = pieces[p]; pieces[p] = t; e -= 1 end end board = Array.new( 64 ); generateBoard( board, pieces ) puts e = 0 for j in 0 .. 7 for i in 0 .. 7 if board[i + 8 * j] == nil; e += 1 else if e > 0; print( e ); e = 0; end print( board[i + 8 * j] ) end end if e > 0; print( e ); e = 0; end if j < 7; print( "/" ); end end print( " w - - 0 1\n" ) for j in 0 .. 7 for i in 0 .. 7 if board[i + j * 8] == nil; print( "." ) else print( board[i + j * 8] ); end end puts end
Generator/Exponential
Ruby
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
# This solution cheats and uses only one generator! def powers(m) return enum_for(__method__, m) unless block_given? 0.step{|n| yield n**m} end def squares_without_cubes return enum_for(__method__) unless block_given? cubes = powers(3) c = cubes.next powers(2) do |s| c = cubes.next while c < s yield s unless c == s end end p squares_without_cubes.take(30).drop(20) # p squares_without_cubes.lazy.drop(20).first(10) # Ruby 2.0+
Generator/Exponential
Ruby from Python
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
def filtered(s1, s2) return enum_for(__method__, s1, s2) unless block_given? v, f = s1.next, s2.next loop do v > f and f = s2.next and next v < f and yield v v = s1.next end end squares, cubes = powers(2), powers(3) f = filtered(squares, cubes) p f.take(30).last(10) # p f.lazy.drop(20).first(10) # Ruby 2.0+
Giuga numbers
Ruby
Definition A '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors '''f''' divide (n/f - 1) exactly. All known Giuga numbers are even though it is not known for certain that there are no odd examples. ;Example 30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and: * 30/2 - 1 = 14 is divisible by 2 * 30/3 - 1 = 9 is divisible by 3 * 30/5 - 1 = 5 is divisible by 5 ;Task Determine and show here the first four Giuga numbers. ;Stretch Determine the fifth Giuga number and any more you have the patience for. ;References * Wikipedia: Giuga number * OEIS:A007850 - Giuga numbers
require 'prime' giuga = (1..).lazy.select do |n| pd = n.prime_division pd.sum{|_, d| d} > 1 && #composite pd.all?{|f, _| (n/f - 1) % f == 0} end p giuga.take(4).to_a
Globally replace text in several files
Ruby
Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
Like Perl: ruby -pi -e "gsub('Goodbye London!', 'Hello New York!')" a.txt b.txt c.txt
Gray code
Ruby
Karnaugh maps in order from left to right or top to bottom. Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] ;Reference * Converting Between Gray and Binary Codes. It includes step-by-step animations.
class Integer # Converts a normal integer to a Gray code. def to_gray raise Math::DomainError, "integer is negative" if self < 0 self ^ (self >> 1) end # Converts a Gray code to a normal integer. def from_gray raise Math::DomainError, "integer is negative" if self < 0 recurse = proc do |i| next 0 if i == 0 o = recurse[i >> 1] << 1 o | (i[0] ^ o[1]) end recurse[self] end end (0..31).each do |number| encoded = number.to_gray decoded = encoded.from_gray printf "%2d : %5b => %5b => %5b : %2d\n", number, number, encoded, decoded, decoded end
Greatest subsequential sum
Ruby
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
[ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5], [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1], [-1, -2, -3, -4, -5], [] ].each do |input| puts "\nInput seq: #{input}" puts " Max sum: %d\n Subseq: %s" % subarray_sum(input) end
Greedy algorithm for Egyptian fractions
Ruby from Python
An Egyptian fraction is the sum of distinct unit fractions such as: :::: \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48}) Each fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction \tfrac{x}{y} to be represented by repeatedly performing the replacement :::: \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil} (simplifying the 2nd term in this replacement as necessary, and where \lceil x \rceil is the ''ceiling'' function). For this task, Proper and improper fractions must be able to be expressed. Proper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that a < b, and improper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n'']. ;Task requirements: * show the Egyptian fractions for: \tfrac{43}{48} and \tfrac{5}{121} and \tfrac{2014}{59} * for all proper fractions, \tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has: ::* the largest number of terms, ::* the largest denominator. * for all one-, two-, and three-digit integers, find and show (as above). {extra credit} ;Also see: * Wolfram MathWorld(tm) entry: Egyptian fraction
def ef(fr) ans = [] if fr >= 1 return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1 intfr = fr.to_i ans, fr = [intfr], fr - intfr end x, y = fr.numerator, fr.denominator while x != 1 ans << Rational(1, (1/fr).ceil) fr = Rational(-y % x, y * (1/fr).ceil) x, y = fr.numerator, fr.denominator end ans << fr end for fr in [Rational(43, 48), Rational(5, 121), Rational(2014, 59)] puts '%s => %s' % [fr, ef(fr).join(' + ')] end lenmax = denommax = [0] for b in 2..99 for a in 1...b fr = Rational(a,b) e = ef(fr) elen, edenom = e.length, e[-1].denominator lenmax = [elen, fr] if elen > lenmax[0] denommax = [edenom, fr] if edenom > denommax[0] end end puts 'Term max is %s with %i terms' % [lenmax[1], lenmax[0]] dstr = denommax[0].to_s puts 'Denominator max is %s with %i digits' % [denommax[1], dstr.size], dstr
Hailstone sequence
Ruby
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
This program uses new methods (Integer#even? and Enumerable#max_by) from Ruby 1.8.7.
Hailstone sequence
Ruby 1.8.7
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
module Hailstone ListNode = Struct.new(:value, :size, :succ) do def each node = self while node yield node.value node = node.succ end end end @@sequence = {1 => ListNode[1,1]} module_function def sequence(n) unless @@sequence[n] m, ary = n, [] until succ = @@sequence[m] ary << m m = m.even? ? (m / 2) : (3 * m + 1) end ary.reverse_each do |m| @@sequence[m] = succ = ListNode[m, succ.size + 1, succ] end end @@sequence[n] end end puts "for n = 27, show sequence length and first and last 4 elements" hs27 = Hailstone.sequence(27).entries p [hs27.size, hs27[0..3], hs27[-4..-1]] # find the longest sequence among n less than 100,000 n = (1 ... 100_000).max_by{|n| Hailstone.sequence(n).size} puts "#{n} has a hailstone sequence length of #{Hailstone.sequence(n).size}" puts "the largest number in that sequence is #{Hailstone.sequence(n).max}"
Harmonic series
Ruby
{{Wikipedia|Harmonic number}} In mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers: '''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n''' The series of harmonic numbers thus obtained is often loosely referred to as the harmonic series. Harmonic numbers are closely related to the Euler-Mascheroni constant. The harmonic series is divergent, albeit quite slowly, and grows toward infinity. ;Task * Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers. * Use that procedure to show the values of the first 20 harmonic numbers. * Find and show the position in the series of the first value greater than the integers 1 through 5 ;Stretch * Find and show the position in the series of the first value greater than the integers 6 through 10 ;Related * [[Egyptian fractions]]
harmonics = Enumerator.new do |y| res = 0 (1..).each {|n| y << res += Rational(1, n) } end n = 20 The first #{n} harmonics (as rationals):"" harmonics.take(n).each_slice(5){|slice| puts "%20s"*slice.size % slice } puts milestones = (1..10).to_a harmonics.each.with_index(1) do |h,i| if h > milestones.first then puts "The first harmonic number > #{milestones.shift} is #{h.to_f} at position #{i}" end break if milestones.empty? end
Harshad or Niven series
Ruby 2.4
The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder. Assume that the series is defined as the numbers in increasing order. ;Task: The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: ::* list the first '''20''' members of the sequence, and ::* list the first Harshad number greater than '''1000'''. Show your output here. ;Related task :* Increasing gaps between consecutive Niven numbers ;See also * OEIS: A005349
harshad = 1.step.lazy.select { |n| n % n.digits.sum == 0 } puts "The first 20 harshard numbers are: \n#{ harshad.first(20) }" puts "The first harshard number > 1000 is #{ harshad.find { |n| n > 1000 } }"
Hash join
Ruby
{| class="wikitable" |- ! Input ! Output |- | {| style="border:none; border-collapse:collapse;" |- | style="border:none" | ''A'' = | style="border:none" | {| class="wikitable" |- ! Age !! Name |- | 27 || Jonah |- | 18 || Alan |- | 28 || Glory |- | 18 || Popeye |- | 28 || Alan |} | style="border:none; padding-left:1.5em;" rowspan="2" | | style="border:none" | ''B'' = | style="border:none" | {| class="wikitable" |- ! Character !! Nemesis |- | Jonah || Whales |- | Jonah || Spiders |- | Alan || Ghosts |- | Alan || Zombies |- | Glory || Buffy |} |- | style="border:none" | ''jA'' = | style="border:none" | Name (i.e. column 1) | style="border:none" | ''jB'' = | style="border:none" | Character (i.e. column 0) |} | {| class="wikitable" style="margin-left:1em" |- ! A.Age !! A.Name !! B.Character !! B.Nemesis |- | 27 || Jonah || Jonah || Whales |- | 27 || Jonah || Jonah || Spiders |- | 18 || Alan || Alan || Ghosts |- | 18 || Alan || Alan || Zombies |- | 28 || Glory || Glory || Buffy |- | 28 || Alan || Alan || Ghosts |- | 28 || Alan || Alan || Zombies |} |} The order of the rows in the output table is not significant. If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
def hashJoin(table1, index1, table2, index2) # hash phase h = table1.group_by {|s| s[index1]} h.default = [] # join phase table2.collect {|r| h[r[index2]].collect {|s| [s, r]} }.flatten(1) end table1 = [[27, "Jonah"], [18, "Alan"], [28, "Glory"], [18, "Popeye"], [28, "Alan"]] table2 = [["Jonah", "Whales"], ["Jonah", "Spiders"], ["Alan", "Ghosts"], ["Alan", "Zombies"], ["Glory", "Buffy"]] hashJoin(table1, 1, table2, 0).each { |row| p row }