title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Haversine formula
Ruby
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
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 deg2rad(lat, long) [lat * PI / 180, long * PI / 180] end bna = [36.12, -86.67] lax = [33.94, -118.4] puts "%.1f" % spherical_distance(bna, lax)
Haversine formula
Ruby from Python
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
include Math def haversine(lat1, lon1, lat2, lon2) r = 6372.8 # Earth radius in kilometers deg2rad = PI/180 # convert degress to radians dLat = (lat2 - lat1) * deg2rad dLon = (lon2 - lon1) * deg2rad lat1 = lat1 * deg2rad lat2 = lat2 * deg2rad a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2 c = 2 * asin(sqrt(a)) r * c end puts "distance is #{haversine(36.12, -86.67, 33.94, -118.40)} km "
Here document
Ruby
A ''here document'' (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a ''here document'' is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block. ;Task: Demonstrate the use of ''here documents'' within the language. ;Related task: * [[Documentation]]
address = <<END 1, High Street, #{town_name}, West Midlands. WM4 5HD. END
Heronian triangles
Ruby
Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by: :::: A = \sqrt{s(s-a)(s-b)(s-c)}, where ''s'' is half the perimeter of the triangle; that is, :::: s=\frac{a+b+c}{2}. '''Heronian triangles''' are triangles whose sides ''and area'' are all integers. : An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle. Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor of all three sides is '''1''' (unity). This will exclude, for example, triangle '''6, 8, 10.''' ;Task: # Create a named function/method/procedure/... that implements Hero's formula. # Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. # Show the count of how many triangles are found. # Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths # Show the first ten ordered triangles in a table of sides, perimeter, and area. # Show a similar ordered table for those triangles with area = 210 Show all output here. '''Note''': when generating triangles it may help to restrict a <= b <= c
class Triangle def self.valid?(a,b,c) # class method short, middle, long = [a, b, c].sort short + middle > long end attr_reader :sides, :perimeter, :area def initialize(a,b,c) @sides = [a, b, c].sort @perimeter = a + b + c s = @perimeter / 2.0 @area = Math.sqrt(s * (s - a) * (s - b) * (s - c)) end def heronian? area == area.to_i end def <=>(other) [area, perimeter, sides] <=> [other.area, other.perimeter, other.sides] end def to_s "%-11s%6d%8.1f" % [sides.join('x'), perimeter, area] end end max, area = 200, 210 prim_triangles = [] 1.upto(max) do |a| a.upto(max) do |b| b.upto(max) do |c| next if a.gcd(b).gcd(c) > 1 prim_triangles << Triangle.new(a, b, c) if Triangle.valid?(a, b, c) end end end sorted = prim_triangles.select(&:heronian?).sort puts "Primitive heronian triangles with sides upto #{max}: #{sorted.size}" puts "\nsides perim. area" puts sorted.first(10).map(&:to_s) puts "\nTriangles with an area of: #{area}" sorted.each{|tr| puts tr if tr.area == area}
Hex words
Ruby
Definition For the purposes of this task a '''hex word''' means a word which (in lower case form) consists entirely of the letters '''a, b, c, d, e''' and '''f'''. ;Task Using unixdict.txt, find all hex words with '''4''' letters or more. Convert each such word to its decimal equivalent and compute its base 10 digital root. Display all three in increasing order of digital root and show the total count of such words. Keeping only words which contain at least '''4''' distinct letters, display the same statistics but in decreasing order of decimal equivalent together with their total count.
def report(a) puts a.each {|hexword| puts "%6s %8d %d" % hexword} puts "Total count of these words: #{a.size}" end hexwords = File.readlines("unixdict.txt", chomp: true).reject{|w| w.size < 4 || w.match?(/[^abcdef]/) } res = hexwords.map{|hw| [hw, hw.to_i(16), 1 + (hw.to_i(16) - 1) % 9]}.sort_by(&:last) report( res ) report( res.reject{|hw| hw[0].chars.uniq.size < 4}.sort_by{|w| -w[1]} )
Hickerson series of almost integers
Ruby
The following function, due to D. Hickerson, is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.) The function is: h(n) = {\operatorname{n}!\over2(\ln{2})^{n+1}} It is said to produce "almost integers" for '''n''' between '''1''' and '''17'''. The purpose of the task is to verify this assertion. Assume that an "almost integer" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation ;Task: Calculate all values of the function checking and stating which are "almost integers". Note: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example: h(18) = 3385534663256845326.39...
require "bigdecimal" LN2 = BigMath::log(2,16) #Use LN2 = Math::log(2) to see the difference with floats FACTORIALS = Hash.new{|h,k| h[k] = k * h[k-1]} FACTORIALS[0] = 1 def hickerson(n) FACTORIALS[n] / (2 * LN2 ** (n+1)) end def nearly_int?(n) int = n.round n.between?(int - 0.1, int + 0.1) end 1.upto(17) do |n| h = hickerson(n) str = nearly_int?(h) ? "nearly integer" : "NOT nearly integer" puts "n:%3i h: %s\t%s" % [n, h.to_s('F')[0,25], str] #increase the 25 to print more digits, there are 856 of them end
History variables
Ruby
''Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.'' ''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables. '' "History Variables: The Semantics, Formal Correctness, and Implementation of History Variables in an Imperative Programming Language" by Mallon and Takaoka Concept also discussed on LtU and Patents.com. ;Task: Demonstrate History variable support: * enable history variable support (if needed) * define a history variable * assign three values * non-destructively display the history * recall the three values. For extra points, if the language of choice does not support history variables, demonstrate how this might be implemented.
foo_hist = [] trace_var(:$foo){|v| foo_hist.unshift(v)} $foo = "apple" $foo = "pear" $foo = "banana" p foo_hist # => ["banana", "pear", "apple"]
Hofstadter-Conway $10,000 sequence
Ruby
The definition of the sequence is colloquially described as: * Starting with the list [1,1], * Take the last number in the list so far: 1, I'll call it x. * Count forward x places from the beginning of the list to find the first number to add (1) * Count backward x places from the end of the list to find the second number to add (1) * Add the two indexed numbers from the list and the result becomes the next number in the list (1+1) * This would then produce [1,1,2] where 2 is the third element of the sequence. Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''. A less wordy description of the sequence is: a(1)=a(2)=1 a(n)=a(a(n-1))+a(n-a(n-1)) The sequence begins: 1, 1, 2, 2, 3, 4, 4, 4, 5, ... Interesting features of the sequence are that: * a(n)/n tends to 0.5 as n grows towards infinity. * a(n)/n where n is a power of 2 is 0.5 * For n>4 the maximal value of a(n)/n between successive powers of 2 decreases. a(n) / n for n in 1..256 The sequence is so named because John Conway offered a prize of $10,000 to the first person who could find the first position, p in the sequence where |a(n)/n| < 0.55 for all n > p It was later found that Hofstadter had also done prior work on the sequence. The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article). ;Task: # Create a routine to generate members of the Hofstadter-Conway $10,000 sequence. # Use it to show the maxima of a(n)/n between successive powers of two up to 2**20 # As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20 ;Also see: * Conways Challenge Sequence, Mallows' own account. * Mathworld Article.
class HofstadterConway10000 def initialize @sequence = [nil, 1, 1] end def [](n) raise ArgumentError, "n must be >= 1" if n < 1 a = @sequence a.length.upto(n) {|i| a[i] = a[a[i-1]] + a[i-a[i-1]] } a[n] end end hc = HofstadterConway10000.new mallows = nil (1...20).each do |i| j = i + 1 max_n, max_v = -1, -1 (2**i .. 2**j).each do |n| v = hc[n].to_f / n max_n, max_v = n, v if v > max_v # Mallows number mallows = n if v >= 0.55 end puts "maximum between 2^%2d and 2^%2d occurs at%7d: %.8f" % [i, j, max_n, max_v] end puts "the mallows number is #{mallows}"
Hofstadter Figure-Figure sequences
Ruby from Tcl
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
$r = [nil, 1] $s = [nil, 2] def buildSeq(n) current = [ $r[-1], $s[-1] ].max while $r.length <= n || $s.length <= n idx = [ $r.length, $s.length ].min - 1 current += 1 if current == $r[idx] + $s[idx] $r << current else $s << current end end end def ffr(n) buildSeq(n) $r[n] end def ffs(n) buildSeq(n) $s[n] end require 'set' require 'test/unit' class TestHofstadterFigureFigure < Test::Unit::TestCase def test_first_ten_R_values r10 = 1.upto(10).map {|n| ffr(n)} assert_equal(r10, [1, 3, 7, 12, 18, 26, 35, 45, 56, 69]) end def test_40_R_and_960_S_are_1_to_1000 rs_values = Set.new rs_values.merge( 1.upto(40).collect {|n| ffr(n)} ) rs_values.merge( 1.upto(960).collect {|n| ffs(n)} ) assert_equal(rs_values, Set.new( 1..1000 )) end end
Hofstadter Figure-Figure sequences
Ruby from Python
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
R = Enumerator.new do |y| y << n = 1 S.each{|s_val| y << n += s_val} end S = Enumerator.new do |y| y << 2 y << 4 u = 5 R.each do |r_val| next if u > r_val (u...r_val).each{|r| y << r} u = r_val+1 end end p R.take(10) p S.take(10) p (R.take(40)+ S.take(960)).sort == (1..1000).to_a
Hofstadter Q sequence
Ruby
The Hofstadter Q sequence is defined as: :: \begin{align} Q(1)&=Q(2)=1, \\ Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2. \end{align} It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence. ;Task: * Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 * Confirm and display that the 1000th term is: 502 ;Optional extra credit * Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term. * Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large. (This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
@cache = [] def Q(n) if @cache[n].nil? case n when 1, 2 then @cache[n] = 1 else @cache[n] = Q(n - Q(n-1)) + Q(n - Q(n-2)) end end @cache[n] end puts "first 10 numbers in the sequence: #{(1..10).map {|n| Q(n)}}" puts "1000'th term: #{Q(1000)}" prev = Q(1) count = 0 2.upto(100_000) do |n| q = Q(n) count += 1 if q < prev prev = q end puts "number of times in the first 100,000 terms where Q(i)<Q(i-1): #{count}"
Horner's rule for polynomial evaluation
Ruby
A fast scheme for evaluating a polynomial such as: : -19+7x-4x^2+6x^3\, when : x=3\;. is to arrange the computation as follows: : ((((0) x + 6) x + (-4)) x + 7) x + (-19)\; And compute the result from the innermost brackets outwards as in this pseudocode: coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order'' x ''':=''' 3 accumulator ''':=''' 0 '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do''' ''# Assumes 1-based indexing for arrays'' accumulator ''':=''' ( accumulator * x ) + coefficients[i] '''done''' ''# accumulator now has the answer'' '''Task Description''' :Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule. Cf. [[Formal power series]]
def horner(coeffs, x) coeffs.reverse.inject(0) {|acc, coeff| acc * x + coeff} end p horner([-19, 7, -4, 6], 3) # ==> 128
ISBN13 check digit
Ruby
Validate the check digit of an ISBN-13 code: ::* Multiply every other digit by '''3'''. ::* Add these numbers and the other digits. ::* Take the remainder of this number after division by '''10'''. ::* If it is '''0''', the ISBN-13 check digit is correct. You might use the following codes for testing: ::::* 978-0596528126 (good) ::::* 978-0596528120 (bad) ::::* 978-1788399081 (good) ::::* 978-1788399083 (bad) Show output here, on this page ;See also: :* for details: 13-digit ISBN method of validation. (installs cookies.)
def validISBN13?(str) cleaned = str.delete("^0-9").chars return false unless cleaned.size == 13 cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0 end isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"] isbns.each{|isbn| puts "#{isbn}: #{validISBN13?(isbn)}" }
I before E except after C
Ruby
The phrase "I before E, except after C" is a widely known mnemonic which is supposed to help when spelling English words. ;Task: Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually: :::# ''"I before E when not preceded by C"'' :::# ''"E before I when preceded by C"'' If both sub-phrases are plausible then the original phrase can be said to be plausible. Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate). ;Stretch goal: As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account. ''Show your output here as well as your program.'' ;cf.: * Schools to rethink 'i before e' - BBC news, 20 June 2009 * I Before E Except After C - QI Series 8 Ep 14, (humorous) * Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
require 'open-uri' plausibility_ratio = 2 counter = Hash.new(0) path = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' rules = [['I before E when not preceded by C:', 'ie', 'ei'], ['E before I when preceded by C:', 'cei', 'cie']] open(path){|f| f.each{|line| line.scan(/ie|ei|cie|cei/){|match| counter[match] += 1 }}} overall_plausible = rules.all? do |(str, x, y)| num_x, num_y, ratio = counter[x], counter[y], counter[x] / counter[y].to_f plausibility = ratio > plausibility_ratio puts str puts "#{x}: #{num_x}; #{y}: #{num_y}; Ratio: #{ratio.round(2)}: #{ plausibility ? 'Plausible' : 'Implausible'}" plausibility end puts "Overall: #{overall_plausible ? 'Plausible' : 'Implausible'}."
Identity matrix
Ruby
Build an identity matrix of a size known at run-time. An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', where the diagonal elements are all '''1'''s (ones), and all the other elements are all '''0'''s (zeroes). I_n = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ \end{bmatrix} ;Related tasks: * [[Spiral matrix]] * [[Zig-zag matrix]] * [[Ulam_spiral_(for_primes)]]
def identity(size) Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}} end [4,5,6].each do |size| puts size, identity(size).map {|r| r.to_s}, "" end
Idiomatically determine all the lowercase and uppercase letters
Ruby
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). ;Task requirements Display the set of all: ::::::* lowercase letters ::::::* uppercase letters that can be used (allowed) by the computer program, where ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. You may want to mention what hardware architecture is being used, and if applicable, the operating system. ;See also * Idiomatically determine all the characters that can be used for symbols.
puts "Lowercase:", [*"a".."z"].join, "Uppercase:", [*"A".."Z"].join
Imaginary base numbers
Ruby 2.3
Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. ''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]'' Other imaginary bases are possible too but are not as widely discussed and aren't specifically named. '''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. At a minimum, support quater-imaginary (base 2i). For extra kudos, support positive or negative bases 2i through 6i (or higher). As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base. See Wikipedia: Quater-imaginary_base for more details. For reference, here are some some decimal and complex numbers converted to quater-imaginary. Base 10 Base 2i 1 1 2 2 3 3 4 10300 5 10301 6 10302 7 10303 8 10200 9 10201 10 10202 11 10203 12 10100 13 10101 14 10102 15 10103 16 10000 Base 10 Base 2i -1 103 -2 102 -3 101 -4 100 -5 203 -6 202 -7 201 -8 200 -9 303 -10 302 -11 301 -12 300 -13 1030003 -14 1030002 -15 1030001 -16 1030000 Base 10 Base 2i 1i 10.2 2i 10.0 3i 20.2 4i 20.0 5i 30.2 6i 30.0 7i 103000.2 8i 103000.0 9i 103010.2 10i 103010.0 11i 103020.2 12i 103020.0 13i 103030.2 14i 103030.0 15i 102000.2 16i 102000.0 Base 10 Base 2i -1i 0.2 -2i 1030.0 -3i 1030.2 -4i 1020.0 -5i 1020.2 -6i 1010.0 -7i 1010.2 -8i 1000.0 -9i 1000.2 -10i 2030.0 -11i 2030.2 -12i 2020.0 -13i 2020.2 -14i 2010.0 -15i 2010.2 -16i 2000.0
# Extend class Integer with a string conveter. class Integer def as_str() return to_s() end end # Extend class Complex with a string conveter (works only with Gaussian integers). class Complex def as_str() return '0' if self == 0 return real.to_i.to_s if imag == 0 return imag.to_i.to_s + 'i' if real == 0 return real.to_i.to_s + '+' + imag.to_i.to_s + 'i' if imag >= 0 return real.to_i.to_s + '-' + (-(imag.to_i)).to_s + 'i' end end # Emit various tables of conversions. 1.step(16) do |gi| puts(" %4s -> %8s -> %4s %4s -> %8s -> %4s" % [gi.as_str, base2i_encode(gi), base2i_decode(base2i_encode(gi)).as_str, (-gi).as_str, base2i_encode(-gi), base2i_decode(base2i_encode(-gi)).as_str]) end puts 1.step(16) do |gi| gi *= 0+1i puts(" %4s -> %8s -> %4s %4s -> %8s -> %4s" % [gi.as_str, base2i_encode(gi), base2i_decode(base2i_encode(gi)).as_str, (-gi).as_str, base2i_encode(-gi), base2i_decode(base2i_encode(-gi)).as_str]) end puts 0.step(3) do |m| 0.step(3) do |l| 0.step(3) do |h| qi = (100 * h + 10 * m + l).to_s gi = base2i_decode(qi) md = base2i_encode(gi).match(/^(?<num>[0-3]+)(?:\.0)?$/) print(" %4s -> %6s -> %4s" % [qi, gi.as_str, md[:num]]) end puts end end
Increasing gaps between consecutive Niven numbers
Ruby
Note: '''Niven''' numbers are also called '''Harshad''' numbers. :::: They are also called '''multidigital''' numbers. '''Niven''' numbers are positive integers which are evenly divisible by the sum of its digits (expressed in base ten). ''Evenly divisible'' means ''divisible with no remainder''. ;Task: :* find the gap (difference) of a Niven number from the previous Niven number :* if the gap is ''larger'' than the (highest) previous gap, then: :::* show the index (occurrence) of the gap (the 1st gap is '''1''') :::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''') :::* show the Niven number that starts the gap :::* show all numbers with comma separators where appropriate (optional) :::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864''' :* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number :* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer :* show all output here, on this page ;Related task: :* Harshad or Niven series. ;Also see: :* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers. :* (PDF) version of the (above) article by Doyon.
nivens = Enumerator.new {|y| (1..).each {|n| y << n if n.remainder(n.digits.sum).zero?} } cur_gap = 0 puts 'Gap Index of gap Starting Niven' nivens.each_cons(2).with_index(1) do |(n1, n2), i| break if i > 10_000_000 if n2-n1 > cur_gap then printf "%3d %15s %15s\n", n2-n1, i, n1 cur_gap = n2-n1 end end
Index finite lists of positive integers
Ruby from Python
It is known that the set of finite lists of positive integers is countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. ;Task: Implement such a mapping: :* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers. :* write a function ''unrank'' which is the ''rank'' inverse function. Demonstrate your solution by: :* picking a random-length list of random positive integers :* turn it into an integer, and :* get the list back. There are many ways to do this. Feel free to choose any one you like. ;Extra credit: Make the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.
def unrank(n) return [0] if n==1 n.to_s(2)[1..-1].split('0',-1).map(&:size) end def rank(x) return 0 if x.empty? ('1' + x.map{ |a| '1'*a }.join('0')).to_i(2) end for x in 0..10 puts "%3d : %-18s: %d" % [x, a=unrank(x), rank(a)] end puts x = [1, 2, 3, 5, 8] puts "#{x} => #{rank(x)} => #{unrank(rank(x))}"
Integer overflow
Ruby
Some languages support one or more integer types of the underlying processor. This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit. The integers supported by such a type can be ''signed'' or ''unsigned''. Arithmetic for machine level integers can often be done by single CPU instructions. This allows high performance and is the main reason to support machine level integers. ;Definition: An integer overflow happens when the result of a computation does not fit into the fixed size integer. The result can be too small or too big to be representable in the fixed size integer. ;Task: When a language has fixed size integer types, create a program that does arithmetic computations for the fixed size integers of the language. These computations must be done such that the result would overflow. The program should demonstrate what the following expressions do. For 32-bit signed integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit signed integer |- | -(-2147483647-1) | 2147483648 |- | 2000000000 + 2000000000 | 4000000000 |- | -2147483647 - 2147483647 | -4294967294 |- | 46341 * 46341 | 2147488281 |- | (-2147483647-1) / -1 | 2147483648 |} For 64-bit signed integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit signed integer |- | -(-9223372036854775807-1) | 9223372036854775808 |- | 5000000000000000000+5000000000000000000 | 10000000000000000000 |- | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |- | 3037000500 * 3037000500 | 9223372037000250000 |- | (-9223372036854775807-1) / -1 | 9223372036854775808 |} For 32-bit unsigned integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit unsigned integer |- | -4294967295 | -4294967295 |- | 3000000000 + 3000000000 | 6000000000 |- | 2147483647 - 4294967295 | -2147483648 |- | 65537 * 65537 | 4295098369 |} For 64-bit unsigned integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit unsigned integer |- | -18446744073709551615 | -18446744073709551615 |- | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |- | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |- | 4294967296 * 4294967296 | 18446744073709551616 |} ;Notes: :* When the integer overflow does trigger an exception show how the exception is caught. :* When the integer overflow produces some value, print it. :* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results. :* This should be done for signed and unsigned integers of various sizes supported by the computer programming language. :* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted. :* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
2.1.1 :001 > a = 2**62 -1 => 4611686018427387903 2.1.1 :002 > a.class => Fixnum 2.1.1 :003 > (b = a + 1).class => Bignum 2.1.1 :004 > (b-1).class => Fixnum
Intersecting number wheels
Ruby
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
groups = [{A: [1, 2, 3]}, {A: [1, :B, 2], B: [3, 4]}, {A: [1, :D, :D], D: [6, 7, 8]}, {A: [1, :B, :C], B: [3, 4], C: [5, :B]} ] groups.each do |group| p group wheels = group.transform_values(&:cycle) res = 20.times.map do el = wheels[:A].next el = wheels[el].next until el.is_a?(Integer) el end puts res.join(" "),"" end
Inverted syntax
Ruby
'''Inverted syntax with conditional expressions''' In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumbrella=true IF raining=true '''Inverted syntax with assignment''' In traditional syntax, assignments are usually expressed with the variable appearing before the expression: a = 6 In inverted syntax, the expression appears before the variable: 6 = a '''Task''' The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.
# Raise ArgumentError if n is negative. if n < 0 then raise ArgumentError, "negative n" end raise ArgumentError, "negative n" if n < 0 # Exit 1 unless we can call Process.fork. unless Process.respond_to? :fork then exit 1 end exit 1 unless Process.respond_to? :fork # Empty an array, printing each element. while ary.length > 0 do puts ary.shift end puts ary.shift while ary.length > 0 # Another way to empty an array, printing each element. until ary.empty? do puts ary.shift end puts ary.shift until ary.empty?
Isograms and heterograms
Ruby
Definitions For the purposes of this task, an '''isogram''' means a string where each character present is used the same number of times and an '''n-isogram''' means an isogram where each character present is used exactly '''n''' times. A '''heterogram''' means a string in which no character occurs more than once. It follows that a '''heterogram''' is the same thing as a '''1-isogram'''. ;Examples ''caucasus'' is a '''2-isogram''' because the letters c, a, u and s all occur twice. ''atmospheric'' is a '''heterogram''' because all its letters are used once only. ;Task Using '''unixdict.txt''' and ignoring capitalization: '''1)''' Find and display here all words which are '''n-isograms''' where '''n > 1'''. Present the results as a single list but sorted as follows: a. By decreasing order of '''n'''; b. Then by decreasing order of word length; c. Then by ascending lexicographic order. '''2)''' Secondly, find and display here all words which are '''heterograms''' and have more than '''10''' characters. Again present the results as a single list but sorted as per b. and c. above. ;Reference * Wikipedia: Heterogram
words = File.readlines("unixdict.txt", chomp: true) isograms = words.group_by do |word| char_counts = word.downcase.chars.tally.values char_counts.first if char_counts.uniq.size == 1 end isograms.delete(nil) isograms.transform_values!{|ar| ar.sort_by{|word| [-word.size, word]} } keys = isograms.keys.sort.reverse keys.each{|k| puts "(#{isograms[k].size}) #{k}-isograms: #{isograms[k]} " if k > 1 } min_chars = 10 large_heterograms = isograms[1].select{|word| word.size > min_chars } puts "" , "(#{large_heterograms.size}) heterograms with more than #{min_chars} chars:" puts large_heterograms
Isqrt (integer square root) of X
Ruby
Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a real non-negative number. Often '''X''' is actually a non-negative integer. For the purposes of this task, '''X''' can be an integer or a real number, but if it simplifies things in your computer programming language, assume it's an integer. One of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or primes) up to the X of that integer, either to find the factors of that integer, or to determine primality. An alternative method for finding the '''Isqrt''' of a number is to calculate: floor( sqrt(X) ) ::* where '''sqrt''' is the square root function for non-negative real numbers, and ::* where '''floor''' is the floor function for real numbers. If the hardware supports the computation of (real) square roots, the above method might be a faster method for small numbers that don't have very many significant (decimal) digits. However, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support. ;Pseudo-code using quadratic residue: For this task, the integer square root of a non-negative number will be computed using a version of ''quadratic residue'', which has the advantage that no ''floating point'' calculations are used, only integer arithmetic. Furthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions. The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support. Pseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers): q <-- 1 /*initialize Q to unity. */ /*find a power of 4 that's greater than X.*/ perform while q <= x /*perform while Q <= X. */ q <-- q * 4 /*multiply Q by four. */ end /*perform*/ /*Q is now greater than X.*/ z <-- x /*set Z to the value of X.*/ r <-- 0 /*initialize R to zero. */ perform while q > 1 /*perform while Q > unity. */ q <-- q / 4 /*integer divide by four. */ t <-- z - r - q /*compute value of T. */ r <-- r / 2 /*integer divide by two. */ if t >= 0 then do z <-- t /*set Z to value of T. */ r <-- r + q /*compute new value of R. */ end end /*perform*/ /*R is now the Isqrt(X). */ /* Sidenote: Also, Z is now the remainder after square root (i.e. */ /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */ Another version for the (above) 1st '''perform''' is: perform until q > X /*perform until Q > X. */ q <-- q * 4 /*multiply Q by four. */ end /*perform*/ Integer square roots of some values: Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9 Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10 Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10 Isqrt( 3) is 1 Isqrt(63) is 7 Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10 Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11 Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11 Isqrt( 7) is 2 Isqrt(67) is 8 Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11 Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12 Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12 ;Task: Compute and show all output here (on this page) for: ::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format. ::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format. ::* use commas in the displaying of larger numbers. You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code. If your computer programming language only supports smaller integers, show what you can. ;Related tasks: :* sequence of non-squares :* integer roots :* square root by hand
module Commatize refine Integer do def commatize self.to_s.gsub( /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1,\\2") end end end using Commatize def isqrt(x) q, r = 1, 0 while (q <= x) do q <<= 2 end while (q > 1) do q >>= 2; t = x-r-q; r >>= 1 if (t >= 0) then x, r = t, r+q end end r end puts (0..65).map{|n| isqrt(n) }.join(" ") 1.step(73, 2) do |n| print "#{n}:\t" puts isqrt(7**n).commatize end
Iterated digits squaring
Ruby
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): : Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page ;Related tasks: * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]]
# Count how many number chains for Natural Numbers < 10**d end with a value of 1. def iterated_square_digit(d) f = Array.new(d+1){|n| (1..n).inject(1, :*)} #Some small factorials g = -> (n) { res = n.digits.sum{|d| d*d} res==89 ? 0 : res } #An array: table[n]==0 means that n translates to 89 and 1 means that n translates to 1 table = Array.new(d*81+1){|n| n.zero? ? 1 : (i=g.call(n))==89 ? 0 : i} table.collect!{|n| n = table[n] while n>1; n} z = 0 #Running count of numbers translating to 1 [*0..9].repeated_combination(d) do |rc| #Iterate over unique digit combinations next if table[rc.inject(0){|g,n| g+n*n}].zero? #Count only ones nn = [0] * 10 #Determine how many numbers this digit combination corresponds to rc.each{|n| nn[n] += 1} z += nn.inject(f[d]){|gn,n| gn / f[n]} #Add to the count of numbers terminating in 1 end puts "\nd=(#{d}) in the range 1 to #{10**d-1}", "#{z} numbers produce 1 and #{10**d-1-z} numbers produce 89" end [8, 11, 14, 17].each do |d| t0 = Time.now iterated_square_digit(d) puts " #{Time.now - t0} sec" end
JSON
Ruby
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
require 'json' ruby_obj = JSON.parse('{"blue": [1, 2], "ocean": "water"}') puts ruby_obj ruby_obj["ocean"] = { "water" => ["fishy", "salty"] } puts JSON.generate(ruby_obj) puts JSON.pretty_generate(ruby_obj)
Jacobi symbol
Ruby from Crystal
The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) * (a | p) 1 if a is a square (mod p) * (a | p) -1 if a is not a square (mod p) * (a | p) 0 if a 0 If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n). ;Task: Calculate the Jacobi symbol (a | n). ;Reference: * Wikipedia article on Jacobi symbol.
def jacobi(a, n) raise ArgumentError.new "n must b positive and odd" if n < 1 || n.even? res = 1 until (a %= n) == 0 while a.even? a >>= 1 res = -res if [3, 5].include? n % 8 end a, n = n, a res = -res if [a % 4, n % 4] == [3, 3] end n == 1 ? res : 0 end puts "Jacobian symbols for jacobi(a, n)" puts "n\\a 0 1 2 3 4 5 6 7 8 9 10" puts "------------------------------------" 1.step(to: 17, by: 2) do |n| printf("%2d ", n) (0..10).each { |a| printf(" % 2d", jacobi(a, n)) } puts end
Jacobsthal numbers
Ruby
'''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 = 0 J1 = 1 Jn = Jn-1 + 2 x Jn-2 Terms may be calculated directly using one of several possible formulas: Jn = ( 2n - (-1)n ) / 3 '''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J0 = 2''' rather than '''J0 = 0'''. Terms may be calculated directly using one of several possible formulas: JLn = 2n + (-1)n '''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''. '''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime. ;Task * Find and display the first 30 '''Jacobsthal numbers''' * Find and display the first 30 '''Jacobsthal-Lucas numbers''' * Find and display the first 20 '''Jacobsthal oblong numbers''' * Find and display at least the first 10 '''Jacobsthal primes''' ;See also ;* Wikipedia: Jacobsthal number ;* Numbers Aplenty - Jacobsthal number ;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers) ;* OEIS:A014551 - Jacobsthal-Lucas numbers. ;* OEIS:A084175 - Jacobsthal oblong numbers ;* OEIS:A049883 - Primes in the Jacobsthal sequence ;* Related task: Fibonacci sequence ;* Related task: Leonardo numbers
require 'prime' def jacobsthal(n) = (2**n + n[0])/3 def jacobsthal_lucas(n) = 2**n + (-1)**n def jacobsthal_oblong(n) = jacobsthal(n) * jacobsthal(n+1) puts "First 30 Jacobsthal numbers:" puts (0..29).map{|n| jacobsthal(n) }.join(" ") puts "\nFirst 30 Jacobsthal-Lucas numbers: " puts (0..29).map{|n| jacobsthal_lucas(n) }.join(" ") puts "\nFirst 20 Jacobsthal-Oblong numbers: " puts (0..19).map{|n| jacobsthal_oblong(n) }.join(" ") puts "\nFirst 10 prime Jacobsthal numbers: " res = (0..).lazy.filter_map do |i| j = jacobsthal(i) j if j.prime? end puts res.take(10).force.join(" ")
Jaro similarity
Ruby
The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match. ;;Definition The Jaro similarity d_j of two given strings s_1 and s_2 is : d_j = \left\{ \begin{array}{l l} 0 & \text{if }m = 0\\ \frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right. Where: * m is the number of ''matching characters''; * t is half the number of ''transpositions''. Two characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters. Each character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one. ;;Example Given the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find: * m = 4 * |s_1| = 6 * |s_2| = 5 * t = 0 We find a Jaro score of: : d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822 ;Task Implement the Jaro algorithm and show the similarity scores for each of the following pairs: * ("MARTHA", "MARHTA") * ("DIXON", "DICKSONX") * ("JELLYFISH", "SMELLYFISH") ; See also * Jaro-Winkler distance on Wikipedia.
def jaro(s, t) return 1.0 if s == t s_len = s.size t_len = t.size match_distance = ([s_len, t_len].max / 2) - 1 s_matches = [] t_matches = [] matches = 0.0 s_len.times do |i| j_start = [0, i-match_distance].max j_end = [i+match_distance, t_len-1].min (j_start..j_end).each do |j| t_matches[j] && next s[i] == t[j] || next s_matches[i] = true t_matches[j] = true matches += 1.0 break end end return 0.0 if matches == 0.0 k = 0 transpositions = 0.0 s_len.times do |i| s_matches[i] || next k += 1 until t_matches[k] s[i] == t[k] || (transpositions += 1.0) k += 1 end ((matches / s_len) + (matches / t_len) + ((matches - transpositions/2.0) / matches)) / 3.0 end %w( MARTHA MARHTA DIXON DICKSONX JELLYFISH SMELLYFISH ).each_slice(2) do |s,t| puts "jaro(#{s.inspect}, #{t.inspect}) = #{'%.10f' % jaro(s, t)}" end
Jewels and stones
Ruby
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct. The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'. Note that: :# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. :# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'. :# The parameters do not need to have exactly the same names. :# Validating the arguments is unnecessary. So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3. This task was inspired by this problem.
stones, jewels = "aAAbbbb", "aA" stones.count(jewels) # => 3
Juggler sequence
Ruby
Background of the '''juggler sequence''': Juggler sequences were publicized by an American mathematician and author Clifford A. Pickover. The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences, much like balls in the hands of a juggler. ;Description A juggler sequence is an integer sequence that starts with a positive integer a[0], with each subsequent term in the sequence being defined by the recurrence relation: a[k + 1] = floor(a[k] ^ 0.5) if a[k] is even ''' ''or'' ''' a[k + 1] = floor(a[k] ^ 1.5) if a[k] is odd If a juggler sequence reaches 1, then all subsequent terms are equal to 1. This is known to be the case for initial terms up to 1,000,000 but it is not known whether all juggler sequences after that will eventually reach 1. ;Task: Compute and show here the following statistics for juggler sequences with an initial term of a[n] where n is between '''20''' and '''39''' inclusive: * l[n] - the number of terms needed to reach 1. * h[n] - the maximum value reached in that sequence. * i[n] - the index of the term (starting from 0) at which the maximum is (first) reached. If your language supports ''big integers'' with an integer square root function, also compute and show here the same statistics for as many as you reasonably can of the following values for n: 113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827 Those with fast languages and fast machines may also like to try their luck at n = 7110201. However, as h[n] for most of these numbers is thousands or millions of digits long, show instead of h[n]: * d[n] - the number of digits in h[n] The results can be (partially) verified against the table here. ;Related tasks: * [[Hailstone sequence]] * [[Yellowstone sequence]] * [[Isqrt_(integer_square_root)_of_X]] ;See also: * [[oeis:A007320]] Number of steps needed for Juggler sequence started at n to reach 1 * [[oeis:A094716]] Largest value in the Juggler sequence started at n
def juggler(k) = k.even? ? Integer.sqrt(k) : Integer.sqrt(k*k*k) (20..39).chain([113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915]).each do |k| k1 = k l = h = i = 0 until k == 1 do h, i = k, l if k > h l += 1 k = juggler(k) end if k1 < 40 then puts "#{k1}: l[n] = #{l}, h[n] = #{h}, i[n] = #{i}" else puts "#{k1}: l[n] = #{l}, d[n] = #{h.to_s.size}, i[n] = #{i}" end end
Julia set
Ruby from AWK
Task Generate and draw a Julia set. ;Related tasks * Mandelbrot Set
def julia(c_real, c_imag) puts Complex(c_real, c_imag) -1.0.step(1.0, 0.04) do |v| puts -1.4.step(1.4, 0.02).map{|h| judge(c_real, c_imag, h, v)}.join end end def judge(c_real, c_imag, x, y) 50.times do z_real = (x * x - y * y) + c_real z_imag = x * y * 2 + c_imag return " " if z_real**2 > 10000 x, y = z_real, z_imag end "#" end julia(-0.8, 0.156)
Jump anywhere
Ruby
Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range. This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions! * Some languages can ''go to'' any global label in a program. * Some languages can break multiple function calls, also known as ''unwinding the call stack''. * Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation). These jumps are not all alike. A simple ''goto'' never touches the call stack. A continuation saves the call stack, so you can continue a function call after it ends. ;Task: Use your language to demonstrate the various types of jumps that it supports. Because the possibilities vary by language, this task is not specific. You have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
Ruby programs almost never use continuations. [[MRI]] copies the call stack when it saves or calls a continuation, so continuations are slow. The next example abuses a continuation to solve [[FizzBuzz#Ruby]]. It is slower and more confusing than an ordinary loop.
Kaprekar numbers
Ruby
A positive integer is a Kaprekar number if: * It is '''1''' (unity) * The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. * The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, .... ;Example process: 10000 (1002) splitting from left to right: * The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive. * Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid. ;Task: Generate and show all Kaprekar numbers less than 10,000. ;Extra credit: Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; * Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g ;Reference: * The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version ;Related task: * [[Casting out nines]]
def kaprekar(n, base = 10) return [1, 1, 1, ""] if n == 1 return if n*(n-1) % (base-1) != 0 # casting out nine sqr = (n ** 2).to_s(base) (1...sqr.length).each do |i| a = sqr[0 ... i] b = sqr[i .. -1] break if b.delete("0").empty? sum = a.to_i(base) + b.to_i(base) return n.to_s(base), sqr, a, b if sum == n end nil end count = 0 1.upto(10_000 - 1) do |i| if result = kaprekar(i) puts "%4d %8d %s + %s" % result count += 1 end end 10_000.upto(1_000_000 - 1) {|i| count += 1 if kaprekar(i)} puts "#{count} kaprekar numbers under 1,000,000" puts "\nbase17 kaprekar numbers under (base10)1,000,000" base = 17 1.upto(1_000_000) do |decimal| if result = kaprekar(decimal, base) puts "%7s %5s %9s %s + %s" % [decimal, *result] end end
Kernighans large earthquake problem
Ruby
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. ;Problem: You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 ;Task: * Create a program or script invocation to find all the events with magnitude greater than 6 * Assuming an appropriate name e.g. "data.txt" for the file: :# Either: Show how your program is invoked to process a data file of that name. :# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
ruby -nae "$F[2].to_f > 6 && print" data.txt A more interesting problem. Print only the events whose magnitude is above average. Contents of the file: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 2000-02-02 Foo 7.7 1959-08-08 Bar 6.2 1849-09-09 Pym 9.0 The command: ruby -e"m=$<.to_a;f=->s{s.split[2].to_f};a=m.reduce(0){|t,s|t+f[s]}/m.size;puts m.select{|s|f[s]>a}" e.txt Output: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 2000-02-02 Foo 7.7 1849-09-09 Pym 9.0
Keyboard input/Obtain a Y or N response
Ruby
Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.
def yesno begin system("stty raw -echo") str = STDIN.getc ensure system("stty -raw echo") end if str == "Y" return true elsif str == "N" return false else raise "Invalid character." end end
Knight's tour
Ruby
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
class Board Cell = Struct.new(:value, :adj) do def self.end=(end_val) @@end = end_val end def try(seq_num) self.value = seq_num return true if seq_num==@@end a = [] adj.each_with_index do |cell, n| a << [wdof(cell.adj)*10+n, cell] if cell.value.zero? end a.sort.each {|_, cell| return true if cell.try(seq_num+1)} self.value = 0 false end def wdof(adj) adj.count {|cell| cell.value.zero?} end end def initialize(rows, cols) @rows, @cols = rows, cols unless defined? ADJACENT # default move (Knight) eval("ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]]") end frame = ADJACENT.flatten.map(&:abs).max @board = Array.new(rows+frame) do |i| Array.new(cols+frame) do |j| (i<rows and j<cols) ? Cell.new(0) : nil # frame (Sentinel value : nil) end end rows.times do |i| cols.times do |j| @board[i][j].adj = ADJACENT.map{|di,dj| @board[i+di][j+dj]}.compact end end Cell.end = rows * cols @format = " %#{(rows * cols).to_s.size}d" end def solve(sx, sy) if (@rows*@cols).odd? and (sx+sy).odd? puts "No solution" else puts (@board[sx][sy].try(1) ? to_s : "No solution") end end def to_s (0...@rows).map do |x| (0...@cols).map{|y| @format % @board[x][y].value}.join end end end def knight_tour(rows=8, cols=rows, sx=rand(rows), sy=rand(cols)) puts "\nBoard (%d x %d), Start:[%d, %d]" % [rows, cols, sx, sy] Board.new(rows, cols).solve(sx, sy) end knight_tour(8,8,3,1) knight_tour(5,5,2,2) knight_tour(4,9,0,0) knight_tour(5,5,0,1) knight_tour(12,12,1,1)
Knuth's algorithm S
Ruby
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). ;The algorithm: :* Select the first n items as the sample as they become available; :* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. :* Repeat 2nd step for any subsequent items. ;The Task: :* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item. :* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S. :* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of: :::# Use the s_of_n_creator with n == 3 to generate an s_of_n. :::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. Note: A class taking n and generating a callable instance/function might also be used. ;Reference: * The Art of Computer Programming, Vol 2, 3.4.2 p.142 ;Related tasks: * [[One of n lines in a file]] * [[Accumulator factory]]
def s_of_n_creator(n) sample = [] i = 0 Proc.new do |item| i += 1 if i <= n sample << item elsif rand(i) < n sample[rand(n)] = item end sample end end frequency = Array.new(10,0) 100_000.times do s_of_n = s_of_n_creator(3) sample = nil (0..9).each {|digit| sample = s_of_n[digit]} sample.each {|digit| frequency[digit] += 1} end (0..9).each {|digit| puts "#{digit}\t#{frequency[digit]}"}
Kolakoski sequence
Ruby
The natural numbers, (excluding zero); with the property that: : ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''. ;Example: This is ''not'' a Kolakoski sequence: 1,1,2,2,2,1,2,2,1,2,... Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this: : Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ... The above gives the RLE of: 2, 3, 1, 2, 1, ... The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''. ;Creating a Kolakoski sequence: Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,.... # We start the sequence s with the first item from the cycle c: 1 # An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s. We started s with 1 and therefore s[k] states that it should appear only the 1 time. Increment k Get the next item from c and append it to the end of sequence s. s will then become: 1, 2 k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2 Increment k Append the next item from the cycle to the list: 1, 2,2, 1 k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1 increment k ... '''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case. ;Task: # Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle. # Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence. # Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE). # Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 20 members of the sequence generated from (2, 1) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1) # Check the sequence againt its RLE. (There are rules on generating Kolakoski sequences from this method that are broken by the last example)
def create_generator(ar) Enumerator.new do |y| cycle = ar.cycle s = [] loop do t = cycle.next s.push(t) v = s.shift y << v (v-1).times{s.push(t)} end end end def rle(ar) ar.slice_when{|a,b| a != b}.map(&:size) end [[20, [1,2]], [20, [2,1]], [30, [1,3,1,2]], [30, [1,3,2,1]]].each do |num,ar| puts "\nFirst #{num} of the sequence generated by #{ar.inspect}:" p res = create_generator(ar).take(num) puts "Possible Kolakoski sequence? #{res.join.start_with?(rle(res).join)}" end
Lah numbers
Ruby
Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets. Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them. Lah numbers obey the identities and relations: L(n, 0), L(0, k) = 0 # for n, k > 0 L(n, n) = 1 L(n, 1) = n! L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers ''or'' L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers ;Task: :* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. :* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n). :* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''. ;See also: :* '''Wikipedia - Lah number''' :* '''OEIS:A105278 - Unsigned Lah numbers''' :* '''OEIS:A008297 - Signed Lah numbers''' ;Related Tasks: :* '''Stirling numbers of the first kind''' :* '''Stirling numbers of the second kind''' :* '''Bell numbers'''
def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*) def lah(n, k) case k when 1 then fact(n) when n then 1 when (..1),(n..) then 0 else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k) end end r = (0..12) puts "Unsigned Lah numbers: L(n, k):" puts "n/k #{r.map{|n| "%11d" % n}.join}" r.each do |row| print "%-4s" % row puts "#{(0..row).map{|col| "%11d" % lah(row,col)}.join}" end puts "\nMaximum value from the L(100, *) row:"; puts (1..100).map{|a| lah(100,a)}.max
Largest int from concatenated ints
Ruby from Tcl
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
def icsort nums nums.sort { |x, y| "#{y}#{x}" <=> "#{x}#{y}" } end [[54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4]].each do |c| p c # prints nicer in Ruby 1.8 puts icsort(c).join end
Largest number divisible by its digits
Ruby
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits. These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the (base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. ;Example: '''135''' is evenly divisible by '''1''', '''3''', and '''5'''. Note that the digit zero (0) can not be in the number as integer division by zero is undefined. The digits must all be unique so a base ten number will have at most '''9''' digits. Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.) ;Stretch goal: Do the same thing for hexadecimal. ;Related tasks: :* gapful numbers. :* palindromic gapful numbers. ;Also see: :* The OEIS sequence: A115569: Lynch-Bell numbers.
magic_number = 9*8*7 div = 9876432.div(magic_number) * magic_number candidates = div.step(0, -magic_number) res = candidates.find do |c| digits = c.digits (digits & [0,5]).empty? && digits == digits.uniq end puts "Largest decimal number is #{res}"
Largest number divisible by its digits
Ruby from Crystal from Kotlin
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits. These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the (base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. ;Example: '''135''' is evenly divisible by '''1''', '''3''', and '''5'''. Note that the digit zero (0) can not be in the number as integer division by zero is undefined. The digits must all be unique so a base ten number will have at most '''9''' digits. Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.) ;Stretch goal: Do the same thing for hexadecimal. ;Related tasks: :* gapful numbers. :* palindromic gapful numbers. ;Also see: :* The OEIS sequence: A115569: Lynch-Bell numbers.
def divByAll(num, digits) digits.all? { |digit| num % digit.to_i(16) == 0 } end magic = 15 * 14 * 13 * 12 * 11 high = (0xfedcba987654321 / magic) * magic high.step(magic, -magic) do |i| s = i.to_s(16) # always generates lower case a-f next if s.include? "0" # can't contain '0' sd = s.chars.uniq next if sd.size != s.size # digits must be unique (puts "Largest hex number is #{i.to_s(16)}"; break) if divByAll(i, sd) end
Largest proper divisor of n
Ruby
a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.
require 'prime' def a(n) return 1 if n == 1 || n.prime? (n/2).downto(1).detect{|d| n.remainder(d) == 0} end (1..100).map{|n| a(n).to_s.rjust(3)}.each_slice(10){|slice| puts slice.join}
Last Friday of each month
Ruby
Write a program or a script that returns the date of the last Fridays 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_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 2012-06-29 2012-07-27 2012-08-31 2012-09-28 2012-10-26 2012-11-30 2012-12-28 ;Related tasks * [[Five weekends]] * [[Day of the week]] * [[Find the last Sunday of each month]]
require 'date' def last_friday(year, month) # Last day of month: Date.new interprets a negative number as a relative month/day from the end of year/month. d = Date.new(year, month, -1) d -= (d.wday - 5) % 7 # Subtract days after Friday. end year = Integer(ARGV.shift) (1..12).each {|month| puts last_friday(year, month)}
Last letter-first letter
Ruby
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category, Child 1: dog Child 2: goldfish Child 1: hippopotamus Child 2: snake ... ;Task: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated. audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask Extra brownie points for dealing with the full list of 646 names.
class LastL_FirstL def initialize(names) @names = names.dup @first = names.group_by {|name| name[0]} @sequences = [] end def add_name(seq) last_letter = seq[-1][-1] potentials = @first.include?(last_letter) ? (@first[last_letter] - seq) : [] if potentials.empty? @sequences << seq else potentials.each {|name| add_name(seq + [name])} end end def search @names.each {|name| add_name [name]} max = @sequences.max_by {|seq| seq.length}.length max_seqs = @sequences.select {|seq| seq.length == max} puts "there are #{@sequences.length} possible sequences" puts "the longest is #{max} names long" puts "there are #{max_seqs.length} such sequences. one is:" max_seqs.last.each_with_index {|name, idx| puts " %2d %s" % [idx+1, name]} end end names = %w{ audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask } lf = LastL_FirstL.new(names) lf.search
Latin Squares in reduced form
Ruby from D
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained. For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row. Demonstrate by: * displaying the four reduced Latin Squares of order 4. * for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
def printSquare(a) for row in a print row, "\n" end print "\n" end def dList(n, start) start = start - 1 # use 0 based indexing a = Array.new(n) {|i| i} a[0], a[start] = a[start], a[0] a[1..] = a[1..].sort first = a[1] r = [] recurse = lambda {|last| if last == first then # bottom of recursion, reached once for each permutation # test if permutation is deranged a[1..].each_with_index {|v, j| if j + 1 == v then return # no, ignore it end } # yes, save a copy with 1 based indexing b = a.map { |i| i + 1 } r << b return end i = last while i >= 1 do a[i], a[last] = a[last], a[i] recurse.call(last - 1) a[i], a[last] = a[last], a[i] i = i - 1 end } recurse.call(n - 1) return r end def reducedLatinSquares(n, echo) if n <= 0 then if echo then print "[]\n\n" end return 0 end if n == 1 then if echo then print "[1]\n\n" end return 1 end rlatin = Array.new(n) { Array.new(n, Float::NAN)} # first row for j in 0 .. n - 1 rlatin[0][j] = j + 1 end count = 0 recurse = lambda {|i| rows = dList(n, i) for r in 0 .. rows.length - 1 rlatin[i - 1] = rows[r].dup catch (:outer) do for k in 0 .. i - 2 for j in 1 .. n - 1 if rlatin[k][j] == rlatin[i - 1][j] then if r < rows.length - 1 then throw :outer end if i > 2 then return end end end end if i < n then recurse.call(i + 1) else count = count + 1 if echo then printSquare(rlatin) end end end end } # remaining rows recurse.call(2) return count end def factorial(n) if n == 0 then return 1 end prod = 1 for i in 2 .. n prod = prod * i end return prod end print "The four reduced latin squares of order 4 are:\n" reducedLatinSquares(4, true) print "The size of the set of reduced latin squares for the following orders\n" print "and hence the total number of latin squares of these orders are:\n" for n in 1 .. 6 size = reducedLatinSquares(n, false) f = factorial(n - 1) f = f * f * n * size print "Order %d Size %-4d x %d! x %d! => Total %d\n" % [n, size, n, n - 1, f] end
Law of cosines - triples
Ruby
The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(g) = C2 ;Specific angles: For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation": A2 + B2 = C2 For an angle of '''60o''' this becomes the less familiar equation: A2 + B2 - AB = C2 And finally for an angle of '''120o''' this becomes the equation: A2 + B2 + AB = C2 ;Task: * Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered. * Restrain all sides to the integers '''1..13''' inclusive. * Show how many results there are for each of the three angles mentioned above. * Display results on this page. Note: Triangles with the same length sides but different order are to be treated as the same. ;Optional Extra credit: * How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''. ;Related Task * [[Pythagorean triples]] ;See also: * Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
grouped = (1..13).to_a.repeated_permutation(3).group_by do |a,b,c| sumaabb, ab = a*a + b*b, a*b case c*c when sumaabb then 90 when sumaabb - ab then 60 when sumaabb + ab then 120 end end grouped.delete(nil) res = grouped.transform_values{|v| v.map(&:sort).uniq } res.each do |k,v| puts "For an angle of #{k} there are #{v.size} solutions:" puts v.inspect, "\n" end
Least common multiple
Ruby
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
def gcd(m, n) m, n = n, m % n until n.zero? m.abs end def lcm(*args) args.inject(1) do |m, n| return 0 if n.zero? (m * n).abs / gcd(m, n) end end p lcm 12, 18, 22 p lcm 15, 14, -6, 10, 21
Left factorials
Ruby
'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; the same notation can be confusingly seen being used for the two different definitions. Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: :::::::* !''n''` :::::::* !''n'' :::::::* ''n''! (It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''': ::::: !n = \sum_{k=0}^{n-1} k! :::: where ::::: !0 = 0 ;Task Display the left factorials for: * zero through ten (inclusive) * 20 through 110 (inclusive) by tens Display the length (in decimal digits) of the left factorials for: * 1,000 through 10,000 (inclusive), by thousands. ;Also see: * The OEIS entry: A003422 left factorials * The MathWorld entry: left factorial * The MathWorld entry: factorial sums * The MathWorld entry: subfactorial ;Related task: * permutations/derangements (subfactorials)
tens = 20.step(110, 10) thousands = 1000.step(10_000, 1000) 10001.times do |n| lf = left_fact.next case n when 0..10, *tens puts "!#{n} = #{lf}" when *thousands puts "!#{n} has #{lf.to_s.size} digits" end end
Levenshtein distance
Ruby
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
module Levenshtein def self.distance(a, b) a, b = a.downcase, b.downcase costs = Array(0..b.length) # i == 0 (1..a.length).each do |i| costs[0], nw = i, i - 1 # j == 0; nw is lev(i-1, j) (1..b.length).each do |j| costs[j], nw = [costs[j] + 1, costs[j-1] + 1, a[i-1] == b[j-1] ? nw : nw + 1].min, costs[j] end end costs[b.length] end def self.test %w{kitten sitting saturday sunday rosettacode raisethysword}.each_slice(2) do |a, b| puts "distance(#{a}, #{b}) = #{distance(a, b)}" end end end Levenshtein.test
Levenshtein distance/Alignment
Ruby from Tcl
The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is: P-LACE PALACE ;Task: Write a function that shows the alignment of two strings for the corresponding levenshtein distance. As an example, use the words "rosettacode" and "raisethysword". You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).
require 'lcs' def levenshtein_align(a, b) apos, bpos = LCS.new(a, b).backtrack2 c = "" d = "" x0 = y0 = -1 dx = dy = 0 apos.zip(bpos) do |x,y| diff = x + dx - y - dy if diff < 0 dx -= diff c += "-" * (-diff) elsif diff > 0 dy += diff d += "-" * diff end c += a[x0+1..x] x0 = x d += b[y0+1..y] y0 = y end c += a[x0+1..-1] d += b[y0+1..-1] diff = a.length + y0 - b.length - x0 if diff < 0 c += "-" * (-diff) elsif diff > 0 d += "-" * diff end [c, d] end puts levenshtein_align("rosettacode", "raisethysword")
List rooted trees
Ruby from Java
You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical. If we use a matching pair of parentheses to represent a bag, the ways are: For 1 bag, there's one way: () <- a bag for 2 bags, there's one way: (()) <- one bag in another for 3 bags, there are two: ((())) <- 3 bags nested Russian doll style (()()) <- 2 bags side by side, inside the third for 4 bags, four: (()()()) ((())()) ((()())) (((()))) Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration. It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81. ;Task: Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive. This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size. As an example output, run 5 bags. There should be 9 ways.
TREE_LIST = [] OFFSET = [] for i in 0..31 if i == 1 then OFFSET << 1 else OFFSET << 0 end end def append(t) TREE_LIST << (1 | (t << 1)) end def show(t, l) while l > 0 l = l - 1 if t % 2 == 1 then print '(' else print ')' end t = t >> 1 end end def listTrees(n) for i in OFFSET[n] .. OFFSET[n + 1] - 1 show(TREE_LIST[i], n * 2) print "\n" end end def assemble(n, t, sl, pos, rem) if rem == 0 then append(t) return end if sl > rem then sl = rem pos = OFFSET[sl] elsif pos >= OFFSET[sl + 1] then sl = sl - 1 if sl == 0 then return end pos = OFFSET[sl] end assemble(n, t << (2 * sl) | TREE_LIST[pos], sl, pos, rem - sl) assemble(n, t, sl, pos + 1, rem) end def makeTrees(n) if OFFSET[n + 1] != 0 then return end if n > 0 then makeTrees(n - 1) end assemble(n, 0, n - 1, OFFSET[n - 1], n - 1) OFFSET[n + 1] = TREE_LIST.length() end def test(n) if n < 1 || n > 12 then raise ArgumentError.new("Argument must be between 1 and 12") end append(0) makeTrees(n) print "Number of %d-trees: %d\n" % [n, OFFSET[n + 1] - OFFSET[n]] listTrees(n) end test(5)
Long literals, with continuations
Ruby
This task is about writing a computer program that has long literals (character literals that may require specifying the words/tokens on more than one (source) line, either with continuations or some other method, such as abutments or concatenations (or some other mechanisms). The literal is to be in the form of a "list", a literal that contains many words (tokens) separated by a blank (space), in this case (so as to have a common list), the (English) names of the chemical elements of the periodic table. The list is to be in (ascending) order of the (chemical) element's atomic number: ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...'' ... up to the last known (named) chemical element (at this time). Do not include any of the "unnamed" chemical element names such as: ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium'' To make computer programming languages comparable, the statement widths should be restricted to less than '''81''' bytes (characters), or less if a computer programming language has more restrictive limitations or standards. Also mention what column the programming statements can start in if ''not'' in column one. The list ''may'' have leading/embedded/trailing blanks during the declaration (the actual program statements), this is allow the list to be more readable. The "final" list shouldn't have any leading/trailing or superfluous blanks (when stored in the program's "memory"). This list should be written with the idea in mind that the program ''will'' be updated, most likely someone other than the original author, as there will be newer (discovered) elements of the periodic table being added (possibly in the near future). These future updates should be one of the primary concerns in writing these programs and it should be "easy" for someone else to add chemical elements to the list (within the computer program). Attention should be paid so as to not exceed the ''clause length'' of continued or specified statements, if there is such a restriction. If the limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here. ;Task: :* Write a computer program (by whatever name) to contain a list of the known elements. :* The program should eventually contain a long literal of words (the elements). :* The literal should show how one could create a long list of blank-delineated words. :* The "final" (stored) list should only have a single blank between elements. :* Try to use the most idiomatic approach(es) in creating the final list. :* Use continuation if possible, and/or show alternatives (possibly using concatenation). :* Use a program comment to explain what the continuation character is if it isn't obvious. :* The program should contain a variable that has the date of the last update/revision. :* The program, when run, should display with verbiage: :::* The last update/revision date (and should be unambiguous). :::* The number of chemical elements in the list. :::* The name of the highest (last) element name. Show all output here, on this page.
elements = %w( hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth polonium astatine radon francium radium actinium thorium protactinium uranium neptunium plutonium americium curium berkelium californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium livermorium tennessine oganesson) puts "Last mutation #{ File.mtime(__FILE__) } number of elements: #{elements.size} last element: #{elements.last}"
Long year
Ruby
Most years have 52 weeks, some have 53, according to ISO8601. ;Task: Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
require 'date' def long_year?(year = Date.today.year) Date.new(year, 12, 28).cweek == 53 end (2020..2030).each{|year| puts "#{year} is long? #{ long_year?(year) }." }
Longest common subsequence
Ruby
'''Introduction''' Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string. The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings. Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n. The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''. Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly. We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''. Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly. A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable. A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j]. Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''. According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. '''Background''' Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n''). '''Note''' [Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)''). '''Legend''' A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of matches (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet S of distinct symbols in A + B '''References''' [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, ''pp.'' 275-281] '''Examples''' The sequences "1234" and "1224533324" have an LCS of "1234": '''1234''' '''12'''245'''3'''332'''4''' For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": '''t'''hi'''si'''sa'''test''' '''t'''e'''s'''t'''i'''ng123'''test'''ing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia.
===Recursion=== This solution is similar to the Haskell one. It is slow (The time complexity is exponential.)
Longest common subsequence
Ruby 1.9
'''Introduction''' Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string. The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings. Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n. The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''. Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly. We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''. Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly. A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable. A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j]. Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''. According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. '''Background''' Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n''). '''Note''' [Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)''). '''Legend''' A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of matches (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet S of distinct symbols in A + B '''References''' [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, ''pp.'' 275-281] '''Examples''' The sequences "1234" and "1224533324" have an LCS of "1234": '''1234''' '''12'''245'''3'''332'''4''' For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": '''t'''hi'''si'''sa'''test''' '''t'''e'''s'''t'''i'''ng123'''test'''ing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia.
class LCS SELF, LEFT, UP, DIAG = [0,0], [0,-1], [-1,0], [-1,-1] def initialize(a, b) @m = Array.new(a.length) { Array.new(b.length) } a.each_char.with_index do |x, i| b.each_char.with_index do |y, j| match(x, y, i, j) end end end def match(c, d, i, j) @i, @j = i, j @m[i][j] = compute_entry(c, d) end def lookup(x, y) [@i+x, @j+y] end def valid?(i=@i, j=@j) i >= 0 && j >= 0 end def peek(x, y) i, j = lookup(x, y) valid?(i, j) ? @m[i][j] : 0 end def compute_entry(c, d) c == d ? peek(*DIAG) + 1 : [peek(*LEFT), peek(*UP)].max end def backtrack @i, @j = @m.length-1, @m[0].length-1 y = [] y << @i+1 if backstep? while valid? y.reverse end def backtrack2 @i, @j = @m.length-1, @m[0].length-1 y = [] y << @j+1 if backstep? while valid? [backtrack, y.reverse] end def backstep? backstep = compute_backstep @i, @j = lookup(*backstep) backstep == DIAG end def compute_backstep case peek(*SELF) when peek(*LEFT) then LEFT when peek(*UP) then UP else DIAG end end end def lcs(a, b) walker = LCS.new(a, b) walker.backtrack.map{|i| a[i]}.join end if $0 == __FILE__ puts lcs('thisisatest', 'testing123testing') puts lcs("rosettacode", "raisethysword") end
Longest common substring
Ruby from C#
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
def longest_common_substring(a,b) lengths = Array.new(a.length){Array.new(b.length, 0)} greatestLength = 0 output = "" a.each_char.with_index do |x,i| b.each_char.with_index do |y,j| next if x != y lengths[i][j] = (i.zero? || j.zero?) ? 1 : lengths[i-1][j-1] + 1 if lengths[i][j] > greatestLength greatestLength = lengths[i][j] output = a[i - greatestLength + 1, greatestLength] end end end output end p longest_common_substring("thisisatest", "testing123testing")
Longest increasing subsequence
Ruby
Calculate and show here a longest increasing subsequence of the list: :\{3, 2, 6, 4, 5, 1\} And of the list: :\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} Note that a list may have more than one subsequence that is of the maximum length. ;Ref: # Dynamic Programming #1: Longest Increasing Subsequence on YouTube # An efficient solution can be based on Patience sorting.
Node = Struct.new(:val, :back) def lis(n) pileTops = [] # sort into piles for x in n # binary search low, high = 0, pileTops.size-1 while low <= high mid = low + (high - low) / 2 if pileTops[mid].val >= x high = mid - 1 else low = mid + 1 end end i = low node = Node.new(x) node.back = pileTops[i-1] if i > 0 pileTops[i] = node end result = [] node = pileTops.last while node result.unshift(node.val) node = node.back end result end p lis([3, 2, 6, 4, 5, 1]) p lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])
Lucky and even lucky numbers
Ruby from Python
Note that in the following explanation list indices are assumed to start at ''one''. ;Definition of lucky numbers ''Lucky numbers'' are positive integers that are formed by: # Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ... # Return the first number from the list (which is '''1'''). # (Loop begins here) #* Note then return the second number from the list (which is '''3'''). #* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''7'''). #* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ... #* Note then return the 4th number from the list (which is '''9'''). #* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ... #* Take the 5th, i.e. '''13'''. Remove every 13th. #* Take the 6th, i.e. '''15'''. Remove every 15th. #* Take the 7th, i.e. '''21'''. Remove every 21th. #* Take the 8th, i.e. '''25'''. Remove every 25th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above ''except for the very first step'': # Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ... # Return the first number from the list (which is '''2'''). # (Loop begins here) #* Note then return the second number from the list (which is '''4'''). #* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''6'''). #* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ... #* Take the 4th, i.e. '''10'''. Remove every 10th. #* Take the 5th, i.e. '''12'''. Remove every 12th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Task requirements * Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' * Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: ** missing arguments ** too many arguments ** number (or numbers) aren't legal ** misspelled argument ('''lucky''' or '''evenLucky''') * The command line handling should: ** support mixed case handling of the (non-numeric) arguments ** support printing a particular number ** support printing a range of numbers by their index ** support printing a range of numbers by their values * The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) +-------------------+----------------------------------------------------+ | j | Jth lucky number | | j , lucky | Jth lucky number | | j , evenLucky | Jth even lucky number | | | | | j k | Jth through Kth (inclusive) lucky numbers | | j k lucky | Jth through Kth (inclusive) lucky numbers | | j k evenLucky | Jth through Kth (inclusive) even lucky numbers | | | | | j -k | all lucky numbers in the range j --> |k| | | j -k lucky | all lucky numbers in the range j --> |k| | | j -k evenLucky | all even lucky numbers in the range j --> |k| | +-------------------+----------------------------------------------------+ where |k| is the absolute value of k Demonstrate the program by: * showing the first twenty ''lucky'' numbers * showing the first twenty ''even lucky'' numbers * showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive) * showing all ''even lucky'' numbers in the same range as above * showing the 10,000th ''lucky'' number (extra credit) * showing the 10,000th ''even lucky'' number (extra credit) ;See also: * This task is related to the [[Sieve of Eratosthenes]] task. * OEIS Wiki Lucky numbers. * Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. * Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. * Entry lucky numbers on The Eric Weisstein's World of Mathematics.
def generator(even=false, nmax=1000000) start = even ? 2 : 1 Enumerator.new do |y| n = 1 ary = [0] + (start..nmax).step(2).to_a # adds [0] to revise the 0 beginnings. y << ary[n] while (m = ary[n+=1]) < ary.size y << m (m...ary.size).step(m){|i| ary[i]=nil} ary.compact! # remove nil end # drain ary[n..-1].each{|i| y << i} raise StopIteration end end def lucky(argv) j, k = argv[0].to_i, argv[1].to_i mode = /even/i=~argv[2] ? :'even lucky' : :lucky seq = generator(mode == :'even lucky') ord = ->(n){"#{n}#{(n%100).between?(11,19) ? 'th' : %w[th st nd rd th th th th th th][n%10]}"} if k.zero? puts "#{ord[j]} #{mode} number: #{seq.take(j).last}" elsif 0 < k puts "#{ord[j]} through #{ord[k]} (inclusive) #{mode} numbers", " #{seq.take(k)[j-1..-1]}" else k = -k ary = [] loop do case num=seq.next when 1...j when j..k then ary << num else break end end puts "all #{mode} numbers in the range #{j}..#{k}", " #{ary}" end end if __FILE__ == $0 lucky(ARGV) end
Lychrel numbers
Ruby from Python
::# Take an integer n, greater than zero. ::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n. ::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. ;Example: If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens ''after'' an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called '''Lychrel numbers'''. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. ;Seed and related Lychrel numbers: Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. ;Task: * Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500). * Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found. * Print any seed Lychrel or related number that is itself a palindrome. Show all output here. ;References: * What's special about 196? Numberphile video. * A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed). * Status of the 196 conjecture? Mathoverflow.
require 'set' def add_reverse(num, max_iter=1000) (1..max_iter).each_with_object(Set.new([num])) do |_,nums| num += reverse_int(num) nums << num return nums if palindrome?(num) end end def palindrome?(num) num == reverse_int(num) end def reverse_int(num) num.to_s.reverse.to_i end def split_roots_from_relateds(roots_and_relateds) roots = roots_and_relateds.dup i = 1 while i < roots.length this = roots[i] if roots[0...i].any?{|prev| this.intersect?(prev)} roots.delete_at(i) else i += 1 end end root = roots.map{|each_set| each_set.min} related = roots_and_relateds.map{|each_set| each_set.min} related = related.reject{|n| root.include?(n)} return root, related end def find_lychrel(maxn, max_reversions) series = (1..maxn).map{|n| add_reverse(n, max_reversions*2)} roots_and_relateds = series.select{|s| s.length > max_reversions} split_roots_from_relateds(roots_and_relateds) end maxn, reversion_limit = 10000, 500 puts "Calculations using n = 1..#{maxn} and limiting each search to 2*#{reversion_limit} reverse-digits-and-adds" lychrel, l_related = find_lychrel(maxn, reversion_limit) puts " Number of Lychrel numbers: #{lychrel.length}" puts " Lychrel numbers: #{lychrel}" puts " Number of Lychrel related: #{l_related.length}" pals = (lychrel + l_related).select{|x| palindrome?(x)}.sort puts " Number of Lychrel palindromes: #{pals.length}" puts " Lychrel palindromes: #{pals}"
MAC vendor lookup
Ruby
Every connected device around the world comes with a unique Media Access Control address, or a MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. ;Task: Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. '''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''
require 'net/http' arr = ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21', 'D4:F4:6F:C9:EF:8D', '23:45:67'] arr.each do |addr| vendor = Net::HTTP.get('api.macvendors.com', "/#{addr}/") rescue nil puts "#{addr} #{vendor}" end
Mad Libs
Ruby
{{wikipedia}} Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. ;Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: went for a walk in the park. found a . decided to take it home. Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
puts "Enter a story, terminated by an empty line:" story = "" until (line = gets).chomp.empty? story << line end story.scan(/(?<=[<]).+?(?=[>])/).uniq.each do |var| print "Enter a value for '#{var}': " story.gsub!(/<#{var}>/, gets.chomp) end puts puts story
Magic 8-ball
Ruby
Create Magic 8-Ball. See details at: Magic 8-Ball.
#!/usr/bin/ruby class EightBall def initialize print "Welcome to 8 ball! Ask your question below. " puts "Type 'quit' to exit the program.\n\n" @responses = ["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"] end def ask_question print "Question: " question = gets if question.chomp.eql? "quit" exit(0) end puts "Response: #{@responses.sample} \n\n" end def run loop do ask_question end end end eight_ball = EightBall.new eight_ball.run
Magic squares of doubly even order
Ruby
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). This means that the subsquares also have an even size, which plays a role in the construction. {| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%" |- |'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8''' |- |'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16''' |- |'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41''' |- |'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33''' |- |'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25''' |- |'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17''' |- |'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56''' |- |'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64''' |} ;Task Create a magic square of '''8 x 8'''. ;Related tasks * [[Magic squares of odd order]] * [[Magic squares of singly even order]] ;See also: * Doubly Even Magic Squares (1728.org)
def double_even_magic_square(n) raise ArgumentError, "Need multiple of four" if n%4 > 0 block_size, max = n/4, n*n pre_pat = [true, false, false, true, false, true, true, false] pre_pat += pre_pat.reverse pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size flat_ar = pattern.each_with_index.map{|yes, num| yes ? num+1 : max-num} flat_ar.each_slice(n).to_a end def to_string(square) n = square.size fmt = "%#{(n*n).to_s.size + 1}d" * n square.inject(""){|str,row| str << fmt % row << "\n"} end puts to_string(double_even_magic_square(8))
Magic squares of odd order
Ruby
A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). The numbers are usually (but not always) the first '''N'''2 positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''. {| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%" |- | '''8''' || '''1''' || '''6''' |- | '''3''' || '''5''' || '''7''' |- | '''4''' || '''9''' || '''2''' |} ;Task For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. Optionally, show the ''magic number''. You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''. ; Related tasks * [[Magic squares of singly even order]] * [[Magic squares of doubly even order]] ; See also: * MathWorld(tm) entry: Magic_square * Odd Magic Squares (1728.org)
def odd_magic_square(n) raise ArgumentError "Need odd positive number" if n.even? || n <= 0 n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} } end [3, 5, 9].each do |n| puts "\nSize #{n}, magic sum #{(n*n+1)/2*n}" fmt = "%#{(n*n).to_s.size + 1}d" * n odd_magic_square(n).each{|row| puts fmt % row} end
Magic squares of singly even order
Ruby
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction. ;Task Create a magic square of 6 x 6. ; Related tasks * [[Magic squares of odd order]] * [[Magic squares of doubly even order]] ; See also * Singly Even Magic Squares (1728.org)
def odd_magic_square(n) n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} } end def single_even_magic_square(n) raise ArgumentError, "must be even, but not divisible by 4." unless (n-2) % 4 == 0 raise ArgumentError, "2x2 magic square not possible." if n == 2 order = (n-2)/4 odd_square = odd_magic_square(n/2) to_add = (0..3).map{|f| f*n*n/4} quarts = to_add.map{|f| odd_square.dup.map{|row|row.map{|el| el+f}} } sq = [] quarts[0].zip(quarts[2]){|d1,d2| sq << [d1,d2].flatten} quarts[3].zip(quarts[1]){|d1,d2| sq << [d1,d2].flatten} sq = sq.transpose order.times{|i| sq[i].rotate!(n/2)} swap(sq[0][order], sq[0][-order-1]) swap(sq[order][order], sq[order][-order-1]) (order-1).times{|i| sq[-(i+1)].rotate!(n/2)} randomize(sq) end def swap(a,b) a,b = b,a end def randomize(square) square.shuffle.transpose.shuffle end def to_string(square) n = square.size fmt = "%#{(n*n).to_s.size + 1}d" * n square.inject(""){|str,row| str << fmt % row << "\n"} end puts to_string(single_even_magic_square(6))
Map range
Ruby
Given two ranges: :::* [a_1,a_2] and :::* [b_1,b_2]; :::* then a value s in range [a_1,a_2] :::* is linearly mapped to a value t in range [b_1,b_2] where: :::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)} ;Task: Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range [0, 10] to the range [-1, 0]. ;Extra credit: Show additional idiomatic ways of performing the mapping, using tools available to the language.
def map_range(a, b, s) af, al, bf, bl = a.first, a.last, b.first, b.last bf + (s - af)*(bl - bf).quo(al - af) end (0..10).each{|s| puts "%s maps to %g" % [s, map_range(0..10, -1..0, s)]}
Maximum triangle path sum
Ruby
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. ;Task: Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
triangle = " 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93" ar = triangle.each_line.map{|line| line.split.map(&:to_i)} puts ar.inject([]){|res,x| maxes = [0, *res, 0].each_cons(2).map(&:max) x.zip(maxes).map{|a,b| a+b} }.max # => 1320
McNuggets problem
Ruby from Go
From Wikipedia: The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. ;Task: Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n'' where ''x'', ''y'' and ''z'' are natural numbers).
def mcnugget(limit) sv = (0..limit).to_a (0..limit).step(6) do |s| (0..limit).step(9) do |n| (0..limit).step(20) do |t| sv.delete(s + n + t) end end end sv.max end puts(mcnugget 100)
Memory layout of a data structure
Ruby
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
require 'bit-struct' class RS232_9 < BitStruct unsigned :cd, 1, "Carrier detect" #1 unsigned :rd, 1, "Received data" #2 unsigned :td, 1, "Transmitted data" #3 unsigned :dtr, 1, "Data terminal ready" #4 unsigned :sg, 1, "Signal ground" #5 unsigned :dsr, 1, "Data set ready" #6 unsigned :rts, 1, "Request to send" #7 unsigned :cts, 1, "Clear to send" #8 unsigned :ri, 1, "Ring indicator" #9 def self.new_with_int(value) data = {} fields.each_with_index {|f, i| data[f.name] = value[i]} new(data) end end num = rand(2**9 - 1) puts "num = #{num}" sample1 = RS232_9.new([("%09d" % num.to_s(2)).reverse].pack("B*")) puts sample1.inspect_detailed sample2 = RS232_9.new_with_int(num) puts sample2.inspect_detailed puts "CD is #{sample2.cd == 1 ? 'on' : 'off'}"
Metallic ratios
Ruby 2.3
Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series of related ratios that are referred to as the "'''Metallic ratios'''". The '''Golden ratio''' was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was also known to the early Greeks, though was not named so until later as a nod to the '''Golden ratio''' to which it is closely related. The series has been extended to encompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means''). ''Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".'' '''Metallic ratios''' are the real roots of the general form equation: x2 - bx - 1 = 0 where the integer '''b''' determines which specific one it is. Using the quadratic equation: ( -b +- (b2 - 4ac) ) / 2a = x Substitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get: ( b +- (b2 + 4) ) ) / 2 = x We only want the real root: ( b + (b2 + 4) ) ) / 2 = x When we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''. ( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989... With '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''. ( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562... When the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5''' are sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as standard. After that there isn't really any attempt at standardized names. They are given names here on this page, but consider the names fanciful rather than canonical. Note that technically, '''b''' can be '''0''' for a "smaller" ratio than the '''Golden ratio'''. We will refer to it here as the '''Platinum ratio''', though it is kind-of a degenerate case. '''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions: [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] So, The first ten '''Metallic ratios''' are: :::::: {| class="wikitable" style="text-align: center;" |+ Metallic ratios !Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link |- |Platinum||0||(0 + 4) / 2|| 1||-||- |- |Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]] |- |Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]] |- |Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]] |- |Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]] |- |Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]] |- |Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]] |- |Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]] |- |Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]] |- |Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]] |} There are other ways to find the '''Metallic ratios'''; one, (the focus of this task) is through '''successive approximations of Lucas sequences'''. A traditional '''Lucas sequence''' is of the form: x''n'' = P * x''n-1'' - Q * x''n-2'' and starts with the first 2 values '''0, 1'''. For our purposes in this task, to find the metallic ratios we'll use the form: x''n'' = b * x''n-1'' + x''n-2'' ( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.'' At any rate, when '''b = 1''' we get: x''n'' = x''n-1'' + x''n-2'' 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... more commonly known as the Fibonacci sequence. When '''b = 2''': x''n'' = 2 * x''n-1'' + x''n-2'' 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393... And so on. To find the ratio by successive approximations, divide the ('''n+1''')th term by the '''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio. For '''b = 1''' (Fibonacci sequence): 1/1 = 1 2/1 = 2 3/2 = 1.5 5/3 = 1.666667 8/5 = 1.6 13/8 = 1.625 21/13 = 1.615385 34/21 = 1.619048 55/34 = 1.617647 89/55 = 1.618182 etc. It converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest possible convergence for any irrational number. ;Task For each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''': * Generate the corresponding "Lucas" sequence. * Show here, on this page, at least the first '''15''' elements of the "Lucas" sequence. * Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places. * Show the '''value''' of the '''approximation''' at the required accuracy. * Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?). Optional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places. You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change. ;See also * Wikipedia: Metallic mean * Wikipedia: Lucas sequence
require('bigdecimal') require('bigdecimal/util') # An iterator over the Lucas Sequence for 'b'. # (The special case of: x(n) = b * x(n-1) + x(n-2).) def lucas(b) Enumerator.new do |yielder| xn2 = 1 ; yielder.yield(xn2) xn1 = 1 ; yielder.yield(xn1) loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) } end end # Compute the Metallic Ratio to 'precision' from the Lucas Sequence for 'b'. # (Uses the lucas(b) iterator, above.) # The metallic ratio is approximated by x(n) / x(n-1). # Returns a struct of the approximate metallic ratio (.ratio) and the # number of terms required to achieve the given precision (.terms). def metallic_ratio(b, precision) xn2 = xn1 = prev = this = 0 lucas(b).each.with_index do |xn, inx| case inx when 0 xn2 = BigDecimal(xn) when 1 xn1 = BigDecimal(xn) prev = xn1.div(xn2, 2 * precision).round(precision) else xn2, xn1 = xn1, BigDecimal(xn) this = xn1.div(xn2, 2 * precision).round(precision) return Struct.new(:ratio, :terms).new(prev, inx - 1) if prev == this prev = this end end end NAMES = [ 'Platinum', 'Golden', 'Silver', 'Bronze', 'Copper', 'Nickel', 'Aluminum', 'Iron', 'Tin', 'Lead' ] puts puts('Lucas Sequences...') puts('%1s %s' % ['b', 'sequence']) (0..9).each do |b| puts('%1d %s' % [b, lucas(b).first(15)]) end puts puts('Metallic Ratios to 32 places...') puts('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio']) (0..9).each do |b| rn = metallic_ratio(b, 32) puts('%-9s %1d %3d %s' % [NAMES[b], b, rn.terms, rn.ratio.to_s('F')]) end puts puts('Golden Ratio to 256 places...') puts('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio']) gold_rn = metallic_ratio(1, 256) puts('%-9s %1d %3d %s' % [NAMES[1], 1, gold_rn.terms, gold_rn.ratio.to_s('F')])
Metaprogramming
Ruby
{{omit from|BBC BASIC}} Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
class IDVictim # Create elements of this man, woman, or child's identification. attr_accessor :name, :birthday, :gender, :hometown # Allows you to put in a space for anything which is not covered by the # preexisting elements. def self.new_element(element) attr_accessor element end end
Metronome
Ruby
The task is to implement a metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#!/usr/bin/ruby bpm = Integer(ARGV[0]) rescue 60 # sets BPM by the first command line argument, set to 60 if none provided msr = Integer(ARGV[1]) rescue 4 # sets number of beats in a measure by the second command line argument, set to 4 if none provided i = 0 loop do (msr-1).times do puts "\a" sleep(60.0/bpm) end puts "\aAND #{i += 1}" sleep(60.0/bpm) end
Mian-Chowla sequence
Ruby from Go
The Mian-Chowla sequence is an integer sequence defined recursively. Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences. The sequence starts with: ::a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ::ai + aj is distinct, for all i and j less than or equal to n. ;The Task: :* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence. :* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence. Demonstrating working through the first few terms longhand: ::a1 = 1 ::1 + 1 = 2 Speculatively try a2 = 2 ::1 + 1 = 2 ::1 + 2 = 3 ::2 + 2 = 4 There are no repeated sums so '''2''' is the next number in the sequence. Speculatively try a3 = 3 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 3 = 4 ::2 + 2 = 4 ::2 + 3 = 5 ::3 + 3 = 6 Sum of '''4''' is repeated so '''3''' is rejected. Speculatively try a3 = 4 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 4 = 5 ::2 + 2 = 4 ::2 + 4 = 6 ::4 + 4 = 8 There are no repeated sums so '''4''' is the next number in the sequence. And so on... ;See also: :* OEIS:A005282 Mian-Chowla sequence
require 'set' n, ts, mc, sums = 100, [], [1], Set.new sums << 2 st = Time.now for i in (1 .. (n-1)) for j in mc[i-1]+1 .. Float::INFINITY mc[i] = j for k in (0 .. i) if (sums.include?(sum = mc[k]+j)) ts.clear break end ts << sum end if (ts.length > 0) sums = sums | ts break end end end et = (Time.now - st) * 1000 s = " of the Mian-Chowla sequence are:\n" puts "The first 30 terms#{s}#{mc.slice(0..29).join(' ')}\n\n" puts "Terms 91 to 100#{s}#{mc.slice(90..99).join(' ')}\n\n" puts "Computation time was #{et.round(1)}ms."
Middle three digits
Ruby
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
def middle_three_digits(num) # minus sign doesn't factor into digit count, # and calling #abs acts as a duck-type assertion num = num.abs # convert to string and find length length = (str = num.to_s).length # check validity raise ArgumentError, "Number must have at least three digits" if length < 3 raise ArgumentError, "Number must have an odd number of digits" if length.even? return str[length/2 - 1, 3].to_i end
Mind boggling card trick
Ruby
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. ; 1. Cards. # Create a common deck of cards of 52 cards (which are half red, half black). # Give the pack a good shuffle. ; 2. Deal from the shuffled deck, you'll be creating three piles. # Assemble the cards face down. ## Turn up the ''top card'' and hold it in your hand. ### if the card is black, then add the ''next'' card (unseen) to the "black" pile. ### If the card is red, then add the ''next'' card (unseen) to the "red" pile. ## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness). # Repeat the above for the rest of the shuffled deck. ; 3. Choose a random number (call it '''X''') that will be used to swap cards from the "red" and "black" piles. # Randomly choose '''X''' cards from the "red" pile (unseen), let's call this the "red" bunch. # Randomly choose '''X''' cards from the "black" pile (unseen), let's call this the "black" bunch. # Put the "red" bunch into the "black" pile. # Put the "black" bunch into the "red" pile. # (The above two steps complete the swap of '''X''' cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). ; 4. Order from randomness? # Verify (or not) the mathematician's assertion that: '''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.''' (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
deck = ([:black, :red] * 26 ).shuffle black_pile, red_pile, discard = [], [], [] until deck.empty? do discard << deck.pop discard.last == :black ? black_pile << deck.pop : red_pile << deck.pop end x = rand( [black_pile.size, red_pile.size].min ) red_bunch = x.times.map{ red_pile.delete_at( rand( red_pile.size )) } black_bunch = x.times.map{ black_pile.delete_at( rand( black_pile.size )) } black_pile += red_bunch red_pile += black_bunch puts "The magician predicts there will be #{black_pile.count( :black )} red cards in the other pile. Drumroll... There were #{red_pile.count( :red )}!"
Minimum multiple of m where digital sum equals m
Ruby
Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''. ;Task * Find the first 40 elements of the sequence. ;Stretch * Find the next 30 elements of the sequence. ;See also ;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
a131382 = (0..).lazy.map{|n| (1..).detect{|m|(n*m).digits.sum == n} } a131382.take(70).each_slice(10){|slice| puts "%8d"*slice.size % slice }
Minimum positive multiple in base 10 using only 0 and 1
Ruby from Kotlin
Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''". ;Task: Write a routine to find the B10 of a given integer. E.G. '''n''' '''B10''' '''n''' x '''multiplier''' 1 1 ( 1 x 1 ) 2 10 ( 2 x 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the '''B10''' value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find '''B10''' for: 1998, 2079, 2251, 2277 Stretch goal; find '''B10''' for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation. ;See also: :* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. :* How to find Minimum Positive Multiple in base 10 using only 0 and 1
def mod(m, n) result = m % n if result < 0 then result = result + n end return result end def getA004290(n) if n == 1 then return 1 end arr = Array.new(n) { Array.new(n, 0) } arr[0][0] = 1 arr[0][1] = 1 m = 0 while true m = m + 1 if arr[m - 1][mod(-10 ** m, n)] == 1 then break end arr[m][0] = 1 for k in 1 .. n - 1 arr[m][k] = [arr[m - 1][k], arr[m - 1][mod(k - 10 ** m, n)]].max end end r = 10 ** m k = mod(-r, n) (m - 1).downto(1) { |j| if arr[j - 1][k] == 0 then r = r + 10 ** j k = mod(k - 10 ** j, n) end } if k == 1 then r = r + 1 end return r end testCases = Array(1 .. 10) testCases.concat(Array(95 .. 105)) testCases.concat([297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]) for n in testCases result = getA004290(n) print "A004290(%d) = %d = %d * %d\n" % [n, result, n, result / n] end
Modified random distribution
Ruby
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating random numbers to the probability given by function modifier: while True: random1 = rgen() random2 = rgen() if random2 < modifier(random1): answer = random1 break endif endwhile ;Task: * Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example: modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5) * Create a generator of random numbers with probabilities modified by the above function. * Generate >= 10,000 random numbers subject to the probability modification. * Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated. Show your output here, on this page.
def modifier(x) = (x - 0.5).abs * 2 def mod_rand loop do random1, random2 = rand, rand return random1 if random2 < modifier(random1) end end bins = 15 bin_size = 1.0/bins h = {} (0...bins).each{|b| h[b*bin_size] = 0} tally = 50_000.times.map{ (mod_rand).div(bin_size) * bin_size}.tally(h) m = tally.values.max/40 tally.each {|k,v| puts "%f...%f %s %d" % [k, k+bin_size, "*"*(v/m) , v] }
Modular arithmetic
Ruby
equivalence relation called ''congruence''. For any positive integer p called the ''congruence modulus'', two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that: :a = b + k\,p The corresponding set of multiplicative inverse for this task. Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: :f(x) = x^{100} + x + 1 You will use 13 as the congruence modulus and you will compute f(10). It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
# stripped version of Andrea Fazzi's submission to Ruby Quiz #179 class Modulo include Comparable def initialize(n = 0, m = 13) @n, @m = n % m, m end def to_i @n end def <=>(other_n) @n <=> other_n.to_i end [:+, :-, :*, :**].each do |meth| define_method(meth) { |other_n| Modulo.new(@n.send(meth, other_n.to_i), @m) } end def coerce(numeric) [numeric, @n] end end # Demo x, y = Modulo.new(10), Modulo.new(20) p x > y # true p x == y # false p [x,y].sort #[#<Modulo:0x000000012ae0f8 @n=7, @m=13>, #<Modulo:0x000000012ae148 @n=10, @m=13>] p x + y ##<Modulo:0x0000000117e110 @n=4, @m=13> p 2 + y # 9 p y + 2 ##<Modulo:0x00000000ad1d30 @n=9, @m=13> p x**100 + x +1 ##<Modulo:0x00000000ad1998 @n=1, @m=13>
Modular exponentiation
Ruby
Find the last '''40''' decimal digits of a^b, where ::* a = 2988348162058574136915891421498819466320163312926952423791023078876139 ::* b = 2351399303373464486466122544523690094744975233415544072992656881240319 A computer is too slow to find the entire value of a^b. Instead, the program must use a fast algorithm for modular exponentiation: a^b \mod m. The algorithm must work for any integers a, b, m, where b \ge 0 and m > 0.
a = 2988348162058574136915891421498819466320163312926952423791023078876139 b = 2351399303373464486466122544523690094744975233415544072992656881240319 m = 10**40 puts a.pow(b, m)
Modular inverse
Ruby
From Wikipedia: In modulo ''m'' is an integer ''x'' such that ::a\,x \equiv 1 \pmod{m}. Or in other words, such that: ::\exists k \in\Z,\qquad a\, x = 1 + k\,m It can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task. ;Task: Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language, compute the modular inverse of 42 modulo 2017.
#based on pseudo code from http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2 and from translating the python implementation. def extended_gcd(a, b) last_remainder, remainder = a.abs, b.abs x, last_x, y, last_y = 0, 1, 1, 0 while remainder != 0 last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder) x, last_x = last_x - quotient*x, x y, last_y = last_y - quotient*y, y end return last_remainder, last_x * (a < 0 ? -1 : 1) end def invmod(e, et) g, x = extended_gcd(e, et) if g != 1 raise 'The maths are broken!' end x % et end
Monads/List monad
Ruby
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: #Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) #Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String #Compose the two functions with bind
class Array def bind(f) flat_map(&f) end def self.unit(*args) args end # implementing lift is optional, but is a great helper method for turning # ordinary funcitons into monadic versions of them. def self.lift(f) -> e { self.unit(f[e]) } end end inc = -> n { n + 1 } str = -> n { n.to_s } listy_inc = Array.lift(inc) listy_str = Array.lift(str) Array.unit(3,4,5).bind(listy_inc).bind(listy_str) #=> ["4", "5", "6"] # Note that listy_inc and listy_str cannot be composed directly, # as they don't have compatible type signature. # Due to duck typing (Ruby will happily turn arrays into strings), # in order to show this, a new function will have to be used: doub = -> n { 2*n } listy_doub = Array.lift(doub) [3,4,5].bind(listy_inc).bind(listy_doub) #=> [8, 10, 12] # Direct composition will cause a TypeError, as Ruby cannot evaluate 2*[4, 5, 6] # Using bind with the composition is *supposed* to fail, no matter the programming language. comp = -> f, g {-> x {f[g[x]]}} [3,4,5].bind(comp[listy_doub, listy_inc]) #=> TypeError: Array can't be coerced into Fixnum # Composition needs to be defined in terms of bind class Array def bind_comp(f, g) bind(g).bind(f) end end [3,4,5].bind_comp(listy_doub, listy_inc) #=> [8, 10, 12]
Monads/Maybe monad
Ruby
Demonstrate in your programming language the following: #Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) #Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String #Compose the two functions with bind A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time. A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
class Maybe def initialize(value) @value = value end def map if @value.nil? self else Maybe.new(yield @value) end end end Maybe.new(3).map { |n| 2*n }.map { |n| n+1 } #=> #<Maybe @value=7> Maybe.new(nil).map { |n| 2*n }.map { |n| n+1 } #=> #<Maybe @value=nil> Maybe.new(3).map { |n| nil }.map { |n| n+1 } #=> #<Maybe @value=nil> # alias Maybe#new and write bind to be in line with task class Maybe class << self alias :unit :new end def initialize(value) @value = value end def bind if @value.nil? self else yield @value end end end Maybe.unit(3).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) } #=> #<Maybe @value=7> Maybe.unit(nil).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) } #=> #<Maybe @value=nil>
Monads/Writer monad
Ruby
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: # Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) # Write three simple functions: root, addOne, and half # Derive Writer monad versions of each of these functions # Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
# 20220720 Ruby programming solution class Writer attr_reader :value, :log def initialize(value, log = "New") @value = value if value.is_a? Proc @log = log else @log = log + ": " + @value.to_s end end def self.unit(value, log) Writer.new(value, log) end def bind(mwriter) new_value = mwriter.value.call(@value) new_log = @log + "\n" + mwriter.log self.class.new(new_value, new_log) end end lam_sqrt = ->(number) { Math.sqrt(number) } lam_add_one = ->(number) { number + 1 } lam_half = ->(number) { number / 2.0 } sqrt = Writer.unit( lam_sqrt, "Took square root") add_one = Writer.unit( lam_add_one, "Added one") half = Writer.unit( lam_half, "Divided by 2") m1 = Writer.unit(5, "Initial value") m2 = m1.bind(sqrt).bind(add_one).bind(half) puts "The final value is #{m2.value}\n\n" puts "This value was derived as follows:" puts m2.log
Move-to-front algorithm
Ruby
Given a symbol table of a ''zero-indexed'' array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. ;Encoding algorithm: for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table ;Decoding algorithm: # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table ;Example: Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z''' :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''b'''roood | 1 | 'abcdefghijklmnopqrstuvwxyz' |- | b'''r'''oood | 1 17 | 'bacdefghijklmnopqrstuvwxyz' |- | br'''o'''ood | 1 17 15 | 'rbacdefghijklmnopqstuvwxyz' |- | bro'''o'''od | 1 17 15 0 | 'orbacdefghijklmnpqstuvwxyz' |- | broo'''o'''d | 1 17 15 0 0 | 'orbacdefghijklmnpqstuvwxyz' |- | brooo'''d''' | 1 17 15 0 0 5 | 'orbacdefghijklmnpqstuvwxyz' |} Decoding the indices back to the original symbol order: :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''1''' 17 15 0 0 5 | b | 'abcdefghijklmnopqrstuvwxyz' |- | 1 '''17''' 15 0 0 5 | br | 'bacdefghijklmnopqrstuvwxyz' |- | 1 17 '''15''' 0 0 5 | bro | 'rbacdefghijklmnopqstuvwxyz' |- | 1 17 15 '''0''' 0 5 | broo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 '''0''' 5 | brooo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 0 '''5''' | broood | 'orbacdefghijklmnpqstuvwxyz' |} ;Task: :* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. :* Show the strings and their encoding here. :* Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
module MoveToFront ABC = ("a".."z").to_a.freeze def self.encode(str) ar = ABC.dup str.chars.each_with_object([]) do |char, memo| memo << (i = ar.index(char)) ar = m2f(ar,i) end end def self.decode(indices) ar = ABC.dup indices.each_with_object("") do |i, str| str << ar[i] ar = m2f(ar,i) end end private def self.m2f(ar,i) [ar.delete_at(i)] + ar end end ['broood', 'bananaaa', 'hiphophiphop'].each do |word| p word == MoveToFront.decode(p MoveToFront.encode(p word)) end
Multifactorial
Ruby
The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1). Multifactorials generalize factorials as follows: : n! = n(n-1)(n-2)...(2)(1) : n!! = n(n-2)(n-4)... : n!! ! = n(n-3)(n-6)... : n!! !! = n(n-4)(n-8)... : n!! !! ! = n(n-5)(n-10)... In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: # Write a function that given n and the degree, calculates the multifactorial. # Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. '''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
def multifact(n, d) n.step(1, -d).inject( :* ) end (1..5).each {|d| puts "Degree #{d}: #{(1..10).map{|n| multifact(n, d)}.join "\t"}"}
Multiple distinct objects
Ruby
Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: [[Closures/Value capture]]
[Foo.new] * n # here Foo.new can be any expression that returns a new object Array.new(n, Foo.new)
Multisplit
Ruby
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=". For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. '''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
def multisplit(text, separators) sep_regex = Regexp.union(separators) separator_info = [] pieces = [] i = prev = 0 while i = text.index(sep_regex, i) separator = Regexp.last_match(0) pieces << text[prev .. i-1] separator_info << [separator, i] i = i + separator.length prev = i end pieces << text[prev .. -1] [pieces, separator_info] end p multisplit(text, separators) # => [["a", "", "b", "", "c"], [["!=", 1], ["==", 3], ["=", 6], ["!=", 7]]]
Mutex
Ruby
{{requires|Concurrency}} A '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1. A mutex is said to be seized by a [[task]] decreasing ''k''. It is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access. A [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex. A mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order). Entering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down. =Variants of mutexes= ==Global and local mutexes== Usually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one. ==Reentrant mutex== A reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it. ==Read write mutex== A read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control. =Deadlock prevention= There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem. =Sample implementations / APIs=
# acquire a lock -- block execution until it becomes free an_object.mu_lock # acquire a lock -- return immediately even if not acquired got_lock = an_object.mu_try_lock # have a lock? if an_object.mu_locked? then ... # release the lock an_object.mu_unlock # wrap a lock around a block of code -- block execution until it becomes free an_object.my_synchronize do do critical stuff end
N-queens problem
Ruby
right Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''. For the number of solutions for small values of '''N''', see OEIS: A000170. ;Related tasks: * [[A* search algorithm]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[Peaceful chess queen armies]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
# 1. Divide n by 12. Remember the remainder (n is 8 for the eight queens # puzzle). # 2. Write a list of the even numbers from 2 to n in order. # 3. If the remainder is 3 or 9, move 2 to the end of the list. # 4. Append the odd numbers from 1 to n in order, but, if the remainder is 8, # switch pairs (i.e. 3, 1, 7, 5, 11, 9, …). # 5. If the remainder is 2, switch the places of 1 and 3, then move 5 to the # end of the list. # 6. If the remainder is 3 or 9, move 1 and 3 to the end of the list. # 7. Place the first-column queen in the row with the first number in the # list, place the second-column queen in the row with the second number in # the list, etc. def n_queens(n) if n == 1 return "Q" elsif n < 4 puts "no solutions for n=#{n}" return "" end evens = (2..n).step(2).to_a odds = (1..n).step(2).to_a rem = n % 12 # (1) nums = evens # (2) nums.rotate if rem == 3 or rem == 9 # (3) # (4) if rem == 8 odds = odds.each_slice(2).flat_map(&:reverse) end nums.concat(odds) # (5) if rem == 2 nums[nums.index(1)], nums[nums.index(3)] = nums[nums.index(3)], nums[nums.index(1)] nums << nums.delete(5) end # (6) if rem == 3 or rem == 9 nums << nums.delete(1) nums << nums.delete(3) end # (7) nums.map do |q| a = Array.new(n,".") a[q-1] = "Q" a*(" ") end end (1 .. 15).each {|n| puts "n=#{n}"; puts n_queens(n); puts}
Narcissist
Ruby
Quoting from the Esolangs wiki page: A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]]. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
s = "s = %s%s%s; puts(gets.chomp == (s %% [34.chr, s, 34.chr]) ? 'accept' : 'reject')"; puts(gets.chomp == (s % [34.chr, s, 34.chr]) ? 'accept' : 'reject')
Narcissistic decimal number
Ruby
A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. They are also known as '''Plus Perfect''' numbers. ;An example: ::::* if n is '''153''' ::::* then m, (the number of decimal digits) is '''3''' ::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' ::::* and so '''153''' is a narcissistic decimal number ;Task: Generate and show here the first '''25''' narcissistic decimal numbers. Note: 0^1 = 0, the first in the series. ;See also: * the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers. * MathWorld entry: Narcissistic Number. * Wikipedia entry: Narcissistic number.
class Integer def narcissistic? return false if negative? digs = self.digits m = digs.size digs.map{|d| d**m}.sum == self end end puts 0.step.lazy.select(&:narcissistic?).first(25)
Nautical bell
Ruby
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. ;Related task: * [[Sleep]]
watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ] watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ] words = ["One","Two","Three","Four","Five","Six","Seven","Eight"] sound = "ding!" loop do time = Time.now if time.sec == 0 and time.min % 30 == 0 num = (time.hour * 60 + time.min) / 30 % 8 num = 8 if num == 0 hr_min = time.strftime "%H:%M" idx = watch_ends.find_index {|t| hr_min <= t} text = "%s - %s watch, %s bell%s gone" % [ hr_min, watches[idx], words[num-1], num==1 ? "" : "s" ] bells = (sound * num).gsub(sound + sound) {|dd| dd + ' '} puts "%-45s %s" % [text, bells] end sleep 1 end
Negative base numbers
Ruby 2.3
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia ;Task: *Encode the decimal number 10 as negabinary (expect 11110) *Encode the decimal number 146 as negaternary (expect 21102) *Encode the decimal number 15 as negadecimal (expect 195) *In each of the above cases, convert the encoded number back to decimal. ;extra credit: * supply an integer, that when encoded to base -62 (or something "higher"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.
DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' # convert a base 10 integer into a negative base value (as a string) def negative_base_encode(n, b) raise 'base out of range' if (b < -62) || (b > -2) return '0' if n == 0 revdigs = [] while n != 0 do n, r = n.divmod(b) if r < 0 n += 1 r -= b end revdigs << r end return revdigs.reduce('') { |digstr, digit| DIGITS[digit] + digstr } end # convert a negative base value (as a string) into a base 10 integer def negative_base_decode(n, b) raise 'base out of range' if (b < -62) || (b > -2) value = 0 n.reverse.each_char.with_index do |ch, inx| value += DIGITS.index(ch) * b**inx end return value end # do the task [ [10, -2], [146, -3], [15, -10], [0, -31], [-6221826, -62] ].each do |pair| decimal, base = pair encoded = negative_base_encode(decimal, base) decoded = negative_base_decode(encoded, base) puts("Enc: %8i base %-3i = %5s base %-3i Dec: %5s base %-3i = %8i base %-3i" % [decimal, 10, encoded, base, encoded, base, decoded, 10]) end
Nested function
Ruby
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. ;Task: Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. ;References: :* Nested function
def makeList(separator) counter = 1 makeItem = lambda {|item| result = "#{counter}#{separator}#{item}\n" counter += 1 result } makeItem["first"] + makeItem["second"] + makeItem["third"] end print makeList(". ")
Nim game
Ruby
Nim is a simple game where the second player-if they know the trick-will always win. The game has only 3 rules: ::* start with '''12''' tokens ::* each player takes '''1, 2, or 3''' tokens in turn ::* the player who takes the last token wins. To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. ;Task: Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
[12, 8, 4].each do |remaining| puts "There are #{remaining} dots.\nHow many dots would you like to take? " unless (num=gets.to_i).between?(1, 3) puts "Please enter one of 1, 2 or 3" redo end puts "You took #{num} dots, leaving #{remaining-num}.\nComputer takes #{4-num}.\n\n" end puts "Computer took the last and wins."
Nonoblock
Ruby
Nonogram puzzle. ;Given: * The number of cells in a row. * The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. ;Task: * show all possible positions. * show the number of positions of the blocks for the following cases within the row. * show all output on this page. * use a "neat" diagram of the block positions. ;Enumerate the following configurations: # '''5''' cells and '''[2, 1]''' blocks # '''5''' cells and '''[]''' blocks (no blocks) # '''10''' cells and '''[8]''' blocks # '''15''' cells and '''[2, 3, 2, 3]''' blocks # '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible) ;Example: Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# ;An algorithm: * Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). * The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. * for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block. (This is the algorithm used in the [[Nonoblock#Python]] solution). ;Reference: * The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.
def nonoblocks(cell, blocks) raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1 nblock(cell, blocks, '', []) end def nblock(cell, blocks, position, result) if cell <= 0 result << position[0..cell-1] elsif blocks.empty? or blocks[0].zero? result << position + '.' * cell else rest = cell - blocks.inject(:+) - blocks.size + 2 bl, *brest = blocks rest.times.inject(result) do |res, i| nblock(cell-i-bl-1, brest, position + '.'*i + '#'*bl + '.', res) end end end conf = [[ 5, [2, 1]], [ 5, []], [10, [8]], [15, [2, 3, 2, 3]], [ 5, [2, 3]], ] conf.each do |cell, blocks| begin puts "#{cell} cells and #{blocks} blocks" result = nonoblocks(cell, blocks) puts result, result.size, "" rescue => e p e end end
Numbers which are the cube roots of the product of their proper divisors
Ruby
Example Consider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title. ;Task Compute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors. Also show the '''500th''' and '''5,000th''' such numbers. ;Stretch Compute and show the '''50,000th''' such number. ;Reference * OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors. ;Note OEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.
require 'prime' def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp+1} a111398 = [1].chain (1..).lazy.select{|n| tau(n) == 8} puts "The first 50 numbers which are the cube roots of the products of their proper divisors:" p a111398.first(50) [500, 5000, 50000].each{|n| puts "#{n}th: #{a111398.drop(n-1).next}" }