{"title": "100 doors", "language": "Ruby", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "class Door\n attr_reader :state\n\n def initialize\n @state = :closed\n end\n \n def close\n @state = :closed\n end\n\n def open\n @state = :open\n end\n \n def closed?\n @state == :closed\n end\n \n def open?\n @state == :open\n end\n \n def toggle\n if closed? then open else close end\n end\n \n def to_s\n @state.to_s\n end\nend\n\ndoors = Array.new(100) { Door.new }\n1.upto(100) do |multiplier|\n doors.each_with_index do |door, i|\n door.toggle if (i + 1) % multiplier == 0\n end\nend\n\ndoors.each_with_index { |door, i| puts \"Door #{i+1} is #{door}.\" }"} {"title": "100 prisoners", "language": "Ruby", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "prisoners = [*1..100]\nN = 10_000\ngenerate_rooms = ->{ [nil]+[*1..100].shuffle }\n \nres = N.times.count do\n rooms = generate_rooms[]\n prisoners.all? {|pr| rooms[1,100].sample(50).include?(pr)}\nend\nputs \"Random strategy : %11.4f %%\" % (res.fdiv(N) * 100)\n\nres = N.times.count do\n rooms = generate_rooms[]\n prisoners.all? do |pr|\n cur_room = pr\n 50.times.any? do\n found = (rooms[cur_room] == pr)\n cur_room = rooms[cur_room]\n found\n end\n end\nend\nputs \"Optimal strategy: %11.4f %%\" % (res.fdiv(N) * 100)\n"} {"title": "15 puzzle game", "language": "Ruby", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "require 'io/console'\n\nclass Board\n SIZE = 4\n RANGE = 0...SIZE\n \n def initialize\n width = (SIZE*SIZE-1).to_s.size\n @frame = (\"+\" + \"-\"*(width+2)) * SIZE + \"+\"\n @form = \"| %#{width}d \" * SIZE + \"|\"\n @step = 0\n @orign = [*0...SIZE*SIZE].rotate.each_slice(SIZE).to_a.freeze\n @board = @orign.map{|row | row.dup}\n randomize\n draw\n message\n play\n end\n \n private\n \n def randomize\n @board[0][0], @board[SIZE-1][SIZE-1] = 0, 1\n @board[SIZE-1][0], @board[0][SIZE-1] = @board[0][SIZE-1], @board[SIZE-1][0]\n x, y, dx, dy = 0, 0, 1, 0\n 50.times do\n nx,ny = [[x+dx,y+dy], [x+dy,y-dx], [x-dy,y+dx]]\n .select{|nx,ny| RANGE.include?(nx) and RANGE.include?(ny)}\n .sample\n @board[nx][ny], @board[x][y] = 0, @board[nx][ny]\n x, y, dx, dy = nx, ny, nx-x, ny-y\n end\n @x, @y = x, y \n end\n \n def draw\n puts \"\\e[H\\e[2J\"\n @board.each do |row|\n puts @frame\n puts (@form % row).sub(\" 0 \", \" \")\n end\n puts @frame\n puts \"Step: #{@step}\"\n end\n \n DIR = {up: [-1,0], down: [1,0], left: [0,-1], right: [0,1]}\n def move(direction)\n dx, dy = DIR[direction]\n nx, ny = @x + dx, @y + dy\n if RANGE.include?(nx) and RANGE.include?(ny)\n @board[nx][ny], @board[@x][@y] = 0, @board[nx][ny]\n @x, @y = nx, ny\n @step += 1\n draw\n end\n end\n \n def play\n until @board == @orign\n case key_in\n when \"\\e[A\", \"w\" then move(:up)\n when \"\\e[B\", \"s\" then move(:down)\n when \"\\e[C\", \"d\" then move(:right)\n when \"\\e[D\", \"a\" then move(:left)\n \n when \"q\",\"\\u0003\",\"\\u0004\" then exit\n when \"h\" then message\n end\n end\n \n puts \"Congratulations, you have won!\"\n end\n \n def key_in\n input = STDIN.getch\n if input == \"\\e\" \n 2.times {input << STDIN.getch}\n end\n input\n end\n \n def message\n puts <<~EOM\n Use the arrow-keys or WASD on your keyboard to push board in the given direction. \n PRESS q TO QUIT (or Ctrl-C or Ctrl-D)\n EOM\n end\nend\n\nBoard.new"} {"title": "21 game", "language": "Ruby", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "# 21 Game - an example in Ruby for Rosetta Code.\n\nGOAL = 21\nMIN_MOVE = 1\nMAX_MOVE = 3\n\nDESCRIPTION = \"\n*** Welcome to the 21 Game! ***\n21 is a two player game.\nEach player chooses to add 1, 2 or 3 to a running total.\nThe player whose turn it is when the total reaches 21 will win the game.\nThe running total starts at zero.\n\nThe players start the game in turn.\nEnter q to quit at any time.\n\"\n\n#\n# Returns the best move to play.\n#\ndef best_move(total)\n move = rand(1..3)\n MIN_MOVE.upto(MAX_MOVE) do |i|\n move = i if (total + i - 1) % (MAX_MOVE + 1) == 0\n end\n MIN_MOVE.upto(MAX_MOVE) do |i|\n move = i if total + i == GOAL\n end\n move\nend\n\n#\n# Gets the move of the player.\n#\ndef get_move\n print \"Your choice between #{MIN_MOVE} and #{MAX_MOVE}: \"\n answer = gets\n move = answer.to_i\n until move.between?(MIN_MOVE, MAX_MOVE)\n exit if answer.chomp == 'q'\n print 'Invalid choice. Try again: '\n answer = gets\n move = answer.to_i\n end\n move\nend\n\n#\n# Asks the player to restart a game and returns the answer.\n#\ndef restart?\n print 'Do you want to restart (y/n)? '\n restart = gets.chomp\n until ['y', 'n'].include?(restart)\n print 'Your answer is not a valid choice. Try again: '\n restart = gets.chomp\n end\n restart == 'y'\nend\n\n#\n# Run a game. The +player+ argument is the player that starts:\n# * 1 for human\n# * 0 for computer\n#\ndef game(player)\n total = round = 0\n while total < GOAL\n round += 1\n puts \"--- ROUND #{round} ---\\n\\n\"\n player = (player + 1) % 2\n if player == 0\n move = best_move(total)\n puts \"The computer chooses #{move}.\"\n else\n move = get_move\n end\n total += move\n puts \"Running total is now #{total}.\\n\\n\"\n end\n if player == 0\n puts 'Sorry, the computer has won!'\n return false\n end\n puts 'Well done, you have won!'\n true\nend\n\n# MAIN\nputs DESCRIPTION\nrun = true\ncomputer_wins = human_wins = 0\ngames_counter = player = 1\nwhile run\n puts \"\\n=== START GAME #{games_counter} ===\"\n player = (player + 1) % 2\n if game(player)\n human_wins += 1\n else\n computer_wins += 1\n end\n puts \"\\nComputer wins #{computer_wins} games, you wins #{human_wins} game.\"\n games_counter += 1\n run = restart?\nend\nputs 'Good bye!'\n"} {"title": "24 game", "language": "Ruby", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "class Guess < String\n def self.play\n nums = Array.new(4){rand(1..9)}\n loop do\n result = get(nums).evaluate!\n break if result == 24.0\n puts \"Try again! That gives #{result}!\"\n end\n puts \"You win!\"\n end\n \n def self.get(nums)\n loop do\n print \"\\nEnter a guess using #{nums}: \"\n input = gets.chomp\n return new(input) if validate(input, nums)\n end\n end\n \n def self.validate(guess, nums)\n name, error =\n {\n invalid_character: ->(str){ !str.scan(%r{[^\\d\\s()+*/-]}).empty? },\n wrong_number: ->(str){ str.scan(/\\d/).map(&:to_i).sort != nums.sort },\n multi_digit_number: ->(str){ str.match(/\\d\\d/) }\n }\n .find {|name, validator| validator[guess] }\n \n error ? puts(\"Invalid input of a(n) #{name.to_s.tr('_',' ')}!\") : true\n end\n \n def evaluate!\n as_rat = gsub(/(\\d)/, '\\1r') # r : Rational suffix\n eval \"(#{as_rat}).to_f\"\n rescue SyntaxError\n \"[syntax error]\"\n end\nend\n\nGuess.play"} {"title": "24 game/Solve", "language": "Ruby 2.1", "task": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "class TwentyFourGame\n EXPRESSIONS = [\n '((%dr %s %dr) %s %dr) %s %dr',\n '(%dr %s (%dr %s %dr)) %s %dr',\n '(%dr %s %dr) %s (%dr %s %dr)',\n '%dr %s ((%dr %s %dr) %s %dr)',\n '%dr %s (%dr %s (%dr %s %dr))',\n ]\n \n OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a\n \n def self.solve(digits)\n solutions = []\n perms = digits.permutation.to_a.uniq\n perms.product(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|\n # evaluate using rational arithmetic\n text = expr % [a, op1, b, op2, c, op3, d]\n value = eval(text) rescue next # catch division by zero\n solutions << text.delete(\"r\") if value == 24\n end\n solutions\n end\nend\n\n# validate user input\ndigits = ARGV.map do |arg| \n begin\n Integer(arg)\n rescue ArgumentError\n raise \"error: not an integer: '#{arg}'\"\n end\nend\ndigits.size == 4 or raise \"error: need 4 digits, only have #{digits.size}\"\n\nsolutions = TwentyFourGame.solve(digits)\nif solutions.empty?\n puts \"no solutions\"\nelse\n puts \"found #{solutions.size} solutions, including #{solutions.first}\"\n puts solutions.sort\nend"} {"title": "4-rings or 4-squares puzzle", "language": "Ruby", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "def four_squares(low, high, unique=true, show=unique)\n f = -> (a,b,c,d,e,f,g) {[a+b, b+c+d, d+e+f, f+g].uniq.size == 1}\n if unique\n uniq = \"unique\"\n solutions = [*low..high].permutation(7).select{|ary| f.call(*ary)}\n else\n uniq = \"non-unique\"\n solutions = [*low..high].repeated_permutation(7).select{|ary| f.call(*ary)}\n end\n if show\n puts \" \" + [*\"a\"..\"g\"].join(\" \")\n solutions.each{|ary| p ary}\n end\n puts \"#{solutions.size} #{uniq} solutions in #{low} to #{high}\"\n puts\nend\n\n[[1,7], [3,9]].each do |low, high|\n four_squares(low, high)\nend\nfour_squares(0, 9, false)"} {"title": "99 bottles of beer", "language": "Ruby", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "def bottles(beer, wall = false)\n \"#{beer>0 ? beer : \"no more\"} bottle#{\"s\" if beer!=1} of beer#{\" on the wall\" if wall}\"\nend\n\n99.downto(0) do |remaining|\n puts \"#{bottles(remaining,true).capitalize}, #{bottles(remaining)}.\"\n if remaining==0\n print \"Go to the store and buy some more\"\n remaining=100\n else\n print \"Take one down, pass it around\"\n end\n puts \", #{bottles(remaining-1,true)}.\\n\\n\"\nend"} {"title": "9 billion names of God the integer", "language": "Ruby", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "# Generate IPF triangle\n# Nigel_Galloway: May 1st., 2013.\ndef g(n,g)\n return 1 unless 1 < g and g < n-1\n (2..g).inject(1){|res,q| res + (q > n-g ? 0 : g(n-g,q))}\nend\n \n(1..25).each {|n|\n puts (1..n).map {|g| \"%4s\" % g(n,g)}.join\n}\n"} {"title": "ABC problem", "language": "Ruby", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << \"\"\n\nwords.each do |word|\n blocks = \"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\"\n res = word.each_char.all?{|c| blocks.sub!(/\\w?#{c}\\w?/i, \"\")} #regexps can be interpolated like strings\n puts \"#{word.inspect}: #{res}\"\nend\n"} {"title": "ASCII art diagram converter", "language": "Ruby", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "header = < Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "require \"abbrev\" \n \nFile.read(\"daynames.txt\").each_line do |line|\n next if line.strip.empty?\n abbr = line.split.abbrev.invert\n puts \"Minimum size: #{abbr.values.max_by(&:size).size}\", abbr.inspect, \"\\n\"\nend\n"} {"title": "Abbreviations, easy", "language": "Ruby", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#!/usr/bin/env ruby\n\ncmd_table = File.read(ARGV[0]).split\nuser_str = File.read(ARGV[1]).split\n\nuser_str.each do |abbr|\n candidate = cmd_table.find do |cmd|\n cmd.count('A-Z') <= abbr.length && abbr.casecmp(cmd[0...abbr.length]).zero?\n end\n\n print candidate.nil? ? '*error*' : candidate.upcase\n\n print ' '\nend\n\nputs\n"} {"title": "Abbreviations, simple", "language": "Ruby", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "str = \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\"\n\nRE = /(?[a-zA-Z]+)\\s+(?[a-zA-Z]+)/\nstr = str.upcase\n# add missing wordsizes\n2.times{ str.gsub!(RE){ [ $~[:word1], $~[:word1].size, $~[:word2] ].join(\" \")} }\n\ntable = Hash[*str.split].transform_values(&:to_i)\n\ntest = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\nar = test.split.map do |w|\n (res = table.detect{|k,v| k.start_with?(w.upcase) && w.size >= v}) ? res[0] : \"*error*\"\nend\n\nputs ar.join(\" \")\n"} {"title": "Abelian sandpile model/Identity", "language": "Ruby", "task": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that \ncontain a number from 0 to 3 inclusive. (The numbers are said to represent \ngrains of sand in each area of the sandpile).\n\nE.g. s1 =\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n\nand s2 =\n\n 2 1 3\n 1 0 1\n 0 1 0\n \n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then \nthose areas cause the whole sandpile to become \"unstable\" and the sandpile \nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of \nsand to each of its four horizontal or vertical neighbours. Grains are lost \nat the edge of the grid, but otherwise increase the number in neighbouring \ncells by one, whilst decreasing the count in the toppled cell by four in each \ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n\nThe final result is the stable sandpile on the right. \n\n'''Note:''' The order in which cells are toppled does not affect the final result.\n\n;Task:\n* Create a class or datastructure and functions to represent and operate on sandpiles. \n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:\n\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n\n* Show that s3 + s3_id == s3\n* Show that s3_id + s3_id == s3_id\n\n\nShow confirming output here, with your examples.\n\n\n;References:\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian_sandpile_model\n\n", "solution": "class Sandpile\n \n def initialize(ar) = @grid = ar\n \n def to_a = @grid.dup\n \n def + (other)\n res = self.to_a.zip(other.to_a).map{|row1, row2| row1.zip(row2).map(&:sum) }\n Sandpile.new(res)\n end\n \n def stable? = @grid.flatten.none?{|v| v > 3}\n \n def avalanche \n topple until stable?\n self\n end\n \n def == (other) = self.avalanche.to_a == other.avalanche.to_a\n \n def topple\n a = @grid\n a.each_index do |row|\n a[row].each_index do |col|\n next if a[row][col] < 4 \n a[row+1][col] += 1 unless row == a.size-1\n a[row-1][col] += 1 if row > 0\n a[row][col+1] += 1 unless col == a.size-1\n a[row][col-1] += 1 if col > 0\n a[row][col] -= 4\n end\n end\n self\n end\n \n def to_s = \"\\n\" + @grid.map {|row| row.join(\" \") }.join(\"\\n\") \n \nend\n \nputs \"Sandpile:\"\nputs demo = Sandpile.new( [[4,3,3], [3,1,2],[0,2,3]] )\nputs \"\\nAfter the avalanche:\"\nputs demo.avalanche\nputs \"_\" * 30,\"\"\n \ns1 = Sandpile.new([[1, 2, 0], [2, 1, 1], [0, 1, 3]] )\nputs \"s1: #{s1}\"\ns2 = Sandpile.new([[2, 1, 3], [1, 0, 1], [0, 1, 0]] )\nputs \"\\ns2: #{s2}\"\nputs \"\\ns1 + s2 == s2 + s1: #{s1 + s2 == s2 + s1}\"\nputs \"_\" * 30,\"\"\n \ns3 = Sandpile.new([[3, 3, 3], [3, 3, 3], [3, 3, 3]] )\ns3_id = Sandpile.new([[2, 1, 2], [1, 0, 1], [2, 1, 2]] )\nputs \"s3 + s3_id == s3: #{s3 + s3_id == s3}\"\nputs \"s3_id + s3_id == s3_id: #{s3_id + s3_id == s3_id}\"\n"} {"title": "Abundant odd numbers", "language": "Ruby", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "require \"prime\"\n \nclass Integer\n def proper_divisors\n return [] if self == 1\n primes = prime_division.flat_map{|prime, freq| [prime] * freq}\n (1...primes.size).each_with_object([1]) do |n, res|\n primes.combination(n).map{|combi| res << combi.inject(:*)}\n end.flatten.uniq\n end\nend\n\ndef generator_odd_abundants(from=1)\n from += 1 if from.even?\n Enumerator.new do |y|\n from.step(nil, 2) do |n|\n sum = n.proper_divisors.sum\n y << [n, sum] if sum > n\n end\n end\nend\n\ngenerator_odd_abundants.take(25).each{|n, sum| puts \"#{n} with sum #{sum}\" }\nputs \"\\n%d with sum %#d\" % generator_odd_abundants.take(1000).last \nputs \"\\n%d with sum %#d\" % generator_odd_abundants(1_000_000_000).next\n"} {"title": "Accumulator factory", "language": "Ruby", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "require 'rational'\nrequire 'complex'\ny = accumulator(Rational(2, 3))\nputs y[Rational(1, 2)] # 7/6\nputs y[4] # 31/6\nputs y[Complex(0, 1)] # 31/6+1i\n\nt = accumulator(Time.utc(1999, 8, 7, 6, 5))\n # (Ruby 1.8.6) (Ruby 1.9.2)\nputs t[4] # Sat Aug 07 06:05:04 UTC 1999 1999-08-07 06:05:04 UTC\nputs t[-12 * 60 * 60] # Fri Aug 06 18:05:04 UTC 1999 1999-08-06 18:05:04 UTC\n\nrequire 'matrix'\nm = accumulator(Matrix[[1, 2], [3, 4]])\nputs m[Matrix[[5, 6], [7, 8]]] # Matrix[[6, 8], [10, 12]]"} {"title": "Aliquot sequence classifications", "language": "Ruby from Python", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "def aliquot(n, maxlen=16, maxterm=2**47)\n return \"terminating\", [0] if n == 0\n s = []\n while (s << n).size <= maxlen and n < maxterm\n n = n.proper_divisors.inject(0, :+)\n if s.include?(n)\n case n\n when s[0]\n case s.size\n when 1 then return \"perfect\", s\n when 2 then return \"amicable\", s\n else return \"sociable of length #{s.size}\", s\n end\n when s[-1] then return \"aspiring\", s\n else return \"cyclic back to #{n}\", s\n end\n elsif n == 0 then return \"terminating\", s << 0\n end\n end\n return \"non-terminating\", s\nend\n\nfor n in 1..10\n puts \"%20s: %p\" % aliquot(n)\nend\nputs\nfor n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]\n puts \"%20s: %p\" % aliquot(n)\nend"} {"title": "Amb", "language": "Ruby", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "require \"continuation\"\n\nclass Amb\n class ExhaustedError < RuntimeError; end\n\n def initialize\n @fail = proc { fail ExhaustedError, \"amb tree exhausted\" }\n end\n\n def choose(*choices)\n prev_fail = @fail\n callcc { |sk|\n choices.each { |choice|\n\tcallcc { |fk|\n\t @fail = proc {\n\t @fail = prev_fail\n\t fk.call(:fail)\n\t }\n\t if choice.respond_to? :call\n\t sk.call(choice.call)\n\t else\n\t sk.call(choice)\n\t end\n\t}\n }\n @fail.call\n }\n end\n\n def failure\n choose\n end\n\n def assert(cond)\n failure unless cond\n end\nend\n\nA = Amb.new\nw1 = A.choose(\"the\", \"that\", \"a\")\nw2 = A.choose(\"frog\", \"elephant\", \"thing\")\nw3 = A.choose(\"walked\", \"treaded\", \"grows\")\nw4 = A.choose(\"slowly\", \"quickly\")\n\nA.choose() unless w1[-1] == w2[0]\nA.choose() unless w2[-1] == w3[0]\nA.choose() unless w3[-1] == w4[0]\n\nputs w1, w2, w3, w4"} {"title": "Anagrams/Deranged anagrams", "language": "Ruby", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "def deranged?(a, b)\n a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b}\nend\n\ndef find_derangements(list)\n list.combination(2) {|a,b| return a,b if deranged?(a,b)}\n nil\nend\n\nrequire 'open-uri'\nanagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f|\n f.read.split.group_by {|s| s.each_char.sort}\nend\n\nanagram = anagram.select{|k,list| list.size>1}.sort_by{|k,list| -k.size}\n\nanagram.each do |k,list|\n if derangements = find_derangements(list)\n puts \"Longest derangement anagram: #{derangements}\"\n break\n end\nend"} {"title": "Angle difference between two bearings", "language": "Ruby from C++", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "def getDifference(b1, b2)\n\tr = (b2 - b1) % 360.0\n\t# Ruby modulus has same sign as divisor, which is positive here,\n\t# so no need to consider negative case\n\tif r >= 180.0\n\t\tr -= 360.0\n\tend\n\treturn r\nend\n\nif __FILE__ == $PROGRAM_NAME\n\tputs \"Input in -180 to +180 range\"\n\tputs getDifference(20.0, 45.0)\n\tputs getDifference(-45.0, 45.0)\n\tputs getDifference(-85.0, 90.0)\n\tputs getDifference(-95.0, 90.0)\n\tputs getDifference(-45.0, 125.0)\n\tputs getDifference(-45.0, 145.0)\n\tputs getDifference(-45.0, 125.0)\n\tputs getDifference(-45.0, 145.0)\n\tputs getDifference(29.4803, -88.6381)\n\tputs getDifference(-78.3251, -159.036)\n \n\tputs \"Input in wider range\"\n\tputs getDifference(-70099.74233810938, 29840.67437876723)\n\tputs getDifference(-165313.6666297357, 33693.9894517456)\n\tputs getDifference(1174.8380510598456, -154146.66490124757)\n\tputs getDifference(60175.77306795546, 42213.07192354373)\nend"} {"title": "Anti-primes", "language": "Ruby", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "require 'prime'\ndef num_divisors(n)\n n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } \nend\n\nanti_primes = Enumerator.new do |y| # y is the yielder\n max = 0\n y << 1 # yield 1\n 2.step(nil,2) do |candidate| # nil is taken as Infinity\n num = num_divisors(candidate)\n if num > max\n y << candidate # yield the candidate\n max = num\n end\n end\nend\n\nputs anti_primes.take(20).join(\" \")\n"} {"title": "Apply a digital filter (direct form II transposed)", "language": "Ruby from C#", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "def filter(a,b,signal)\n result = Array.new(signal.length(), 0.0)\n for i in 0..signal.length()-1 do\n tmp = 0.0\n for j in 0 .. b.length()-1 do\n if i - j < 0 then next end\n tmp += b[j] * signal[i - j]\n end\n for j in 1 .. a.length()-1 do\n if i - j < 0 then next end\n tmp -= a[j] * result[i - j]\n end\n tmp /= a[0]\n result[i] = tmp\n end\n return result\nend\n\ndef main\n a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]\n b = [0.16666667, 0.5, 0.5, 0.16666667]\n signal = [\n -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,\n -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,\n 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,\n 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,\n 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589\n ]\n\n result = filter(a,b,signal)\n for i in 0 .. result.length() - 1 do\n print \"%11.8f\" % [result[i]]\n if (i + 1) % 5 == 0 then\n print \"\\n\"\n else\n print \", \"\n end\n end\nend\n\nmain()"} {"title": "Approximate equality", "language": "Ruby", "task": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant. \n\nFor example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by \nabout the 8th significant digit in base 10 arithmetic.\n\n\n;Task:\nCreate a function which returns true if two floating point numbers are approximately equal. \n\n\nThe function should allow for differences in the magnitude of numbers, so that, for example, \n'''100000000000000.01''' may be approximately equal to '''100000000000000.011''', \neven though '''100.01''' is not approximately equal to '''100.011'''.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')\n:# 100.01, 100.011 (note: should return ''false'')\n:# 10000000000000.001 / 10000.0, 1000000000.0000001000\n:# 0.001, 0.0010000001\n:# 0.000000000000000000000101, 0.0\n:# sqrt(2) * sqrt(2), 2.0\n:# -sqrt(2) * sqrt(2), -2.0\n:# 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.\n\n\n__TOC__\n\n", "solution": "require \"bigdecimal\"\n\ntestvalues = [[100000000000000.01, 100000000000000.011],\n [100.01, 100.011],\n [10000000000000.001 / 10000.0, 1000000000.0000001000],\n [0.001, 0.0010000001],\n [0.000000000000000000000101, 0.0],\n [(2**0.5) * (2**0.5), 2.0],\n [-(2**0.5) * (2**0.5), -2.0],\n [BigDecimal(\"3.14159265358979323846\"), 3.14159265358979324],\n [Float::NAN, Float::NAN,],\n [Float::INFINITY, Float::INFINITY],\n ]\n\nclass Numeric\n def close_to?(num, tol = Float::EPSILON)\n return true if self == num\n return false if (self.to_f.nan? or num.to_f.nan?) # NaN is not even close to itself\n return false if [self, num].count( Float::INFINITY) == 1 # Infinity is only close to itself\n return false if [self, num].count(-Float::INFINITY) == 1\n (self-num).abs <= tol * ([self.abs, num.abs].max)\n end\nend\n\ntestvalues.each do |a,b|\n puts \"#{a} #{a.close_to?(b) ? '\u2248' : '\u2249'} #{b}\"\nend\n"} {"title": "Arithmetic-geometric mean", "language": "Ruby", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "# The flt package (http://flt.rubyforge.org/) is useful for high-precision floating-point math.\n# It lets us control 'context' of numbers, individually or collectively -- including precision\n# (which adjusts the context's value of epsilon accordingly).\n\nrequire 'flt'\ninclude Flt\n\nBinNum.Context.precision = 512 # default 53 (bits)\n\ndef agm(a,g)\n new_a = BinNum a\n new_g = BinNum g\n while new_a - new_g > new_a.class.Context.epsilon do\n old_g = new_g\n new_g = (new_a * new_g).sqrt\n new_a = (old_g + new_a) * 0.5\n end\n new_g\nend\n\nputs agm(1, 1 / BinNum(2).sqrt)"} {"title": "Arithmetic-geometric mean/Calculate Pi", "language": "Ruby", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "# Calculate Pi using the Arithmetic Geometric Mean of 1 and 1/sqrt(2)\n#\n#\n# Nigel_Galloway\n# March 8th., 2012.\n#\nrequire 'flt'\nFlt::BinNum.Context.precision = 8192\na = n = 1\ng = 1 / Flt::BinNum(2).sqrt\nz = 0.25\n(0..17).each{\n x = [(a + g) * 0.5, (a * g).sqrt]\n var = x[0] - a\n z -= var * var * n\n n += n\n a = x[0]\n g = x[1]\n}\nputs a * a / z"} {"title": "Arithmetic evaluation", "language": "Ruby", "task": "Create a program which parses and evaluates arithmetic expressions.\n;Requirements:\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input. \n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) \n* The expression will be a string or list of symbols like \"(1+3)*7\". \n* The four symbols + - * / must be supported as binary operators with conventional precedence rules. \n* Precedence-control parentheses must also be supported.\n\n\n;Note:\nFor those who don't remember, mathematical precedence is as follows:\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\n\n;C.f: \n* [[24 game Player]].\n* [[Parsing/RPN calculator algorithm]].\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "$op_priority = {\"+\" => 0, \"-\" => 0, \"*\" => 1, \"/\" => 1}\n\nclass TreeNode\n OP_FUNCTION = {\n \"+\" => lambda {|x, y| x + y},\n \"-\" => lambda {|x, y| x - y},\n \"*\" => lambda {|x, y| x * y},\n \"/\" => lambda {|x, y| x / y}}\n attr_accessor :info, :left, :right\n \n def initialize(info)\n @info = info\n end\n \n def leaf?\n @left.nil? and @right.nil?\n end\n \n def to_s(order)\n if leaf?\n @info\n else\n left_s, right_s = @left.to_s(order), @right.to_s(order)\n \n strs = case order\n when :prefix then [@info, left_s, right_s]\n when :infix then [left_s, @info, right_s]\n when :postfix then [left_s, right_s, @info]\n else []\n end\n \n \"(\" + strs.join(\" \") + \")\"\n end\n end\n \n def eval\n if !leaf? and operator?(@info)\n OP_FUNCTION[@info].call(@left.eval, @right.eval)\n else\n @info.to_f\n end\n end\nend\n\ndef tokenize(exp)\n exp\n .gsub('(', ' ( ')\n .gsub(')', ' ) ')\n .gsub('+', ' + ')\n .gsub('-', ' - ')\n .gsub('*', ' * ')\n .gsub('/', ' / ')\n .split(' ')\nend\n\ndef operator?(token)\n $op_priority.has_key?(token)\nend\n\ndef pop_connect_push(op_stack, node_stack)\n temp = op_stack.pop\n temp.right = node_stack.pop\n temp.left = node_stack.pop\n node_stack.push(temp)\nend\n\ndef infix_exp_to_tree(exp)\n tokens = tokenize(exp)\n op_stack, node_stack = [], []\n \n tokens.each do |token|\n if operator?(token)\n # clear stack of higher priority operators\n until (op_stack.empty? or\n op_stack.last.info == \"(\" or\n $op_priority[op_stack.last.info] < $op_priority[token])\n pop_connect_push(op_stack, node_stack)\n end\n \n op_stack.push(TreeNode.new(token))\n elsif token == \"(\"\n op_stack.push(TreeNode.new(token))\n elsif token == \")\"\n while op_stack.last.info != \"(\"\n pop_connect_push(op_stack, node_stack)\n end\n \n # throw away the '('\n op_stack.pop\n else\n node_stack.push(TreeNode.new(token))\n end\n end\n \n until op_stack.empty?\n pop_connect_push(op_stack, node_stack)\n end\n \n node_stack.last\nend"} {"title": "Ascending primes", "language": "Ruby", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "require 'prime'\n\ndigits = [9,8,7,6,5,4,3,2,1]\nres = 1.upto(digits.size).flat_map do |n|\n digits.combination(n).filter_map do |set|\n candidate = set.join.to_i\n candidate if candidate.prime?\n end.reverse\n end\n\n puts res.join(\",\")"} {"title": "Associative array/Merging", "language": "Ruby", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "base = {\"name\" => \"Rocket Skates\", \"price\" => 12.75, \"color\" => \"yellow\"}\nupdate = {\"price\" => 15.25, \"color\" => \"red\", \"year\" => 1974}\n\nresult = base.merge(update)\np result"} {"title": "Attractive numbers", "language": "Ruby", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "require \"prime\"\n \np (1..120).select{|n| n.prime_division.sum(&:last).prime? }\n"} {"title": "Average loop length", "language": "Ruby", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "class Integer\n def factorial\n self == 0 ? 1 : (1..self).inject(:*)\n end\nend\n\ndef rand_until_rep(n)\n rands = {}\n loop do\n r = rand(1..n)\n return rands.size if rands[r]\n rands[r] = true\n end\nend\n\nruns = 1_000_000\n\nputs \" N average exp. diff \",\n \"=== ======== ======== ===========\"\n(1..20).each do |n|\n sum_of_runs = runs.times.inject(0){|sum, _| sum += rand_until_rep(n)}\n avg = sum_of_runs / runs.to_f\n analytical = (1..n).inject(0){|sum, i| sum += (n.factorial / (n**i).to_f / (n-i).factorial)}\n puts \"%3d %8.4f %8.4f (%8.4f%%)\" % [n, avg, analytical, (avg/analytical - 1)*100]\nend"} {"title": "Averages/Mean angle", "language": "Ruby", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core.\n\ndef deg2rad(d)\n d * Math::PI / 180\nend\n \ndef rad2deg(r)\n r * 180 / Math::PI\nend\n\ndef mean_angle(deg)\n rad2deg((deg.inject(0) {|z, d| z + Complex.polar(1, deg2rad(d))} / deg.length).arg)\nend\n\n[[350, 10], [90, 180, 270, 360], [10, 20, 30]].each {|angles|\n puts \"The mean angle of %p is: %f degrees\" % [angles, mean_angle(angles)]\n}"} {"title": "Averages/Pythagorean means", "language": "Ruby 1.9+", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "class Array\n def arithmetic_mean\n inject(0.0, :+) / length\n end\n \n def geometric_mean\n inject(:*) ** (1.0 / length)\n end\n \n def harmonic_mean\n length / inject(0.0) {|s, m| s + 1.0/m}\n end\nend\n\nclass Range\n def method_missing(m, *args)\n case m\n when /_mean$/ then to_a.send(m)\n else super\n end\n end\nend\n\np a = (1..10).arithmetic_mean\np g = (1..10).geometric_mean\np h = (1..10).harmonic_mean\n# is h < g < a ??\np g.between?(h, a)"} {"title": "Averages/Root mean square", "language": "Ruby", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "class Array\n def quadratic_mean\n Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length )\n end\nend\n\nclass Range\n def quadratic_mean\n self.to_a.quadratic_mean\n end\nend\n\n(1..10).quadratic_mean # => 6.2048368229954285"} {"title": "Babbage problem", "language": "Ruby", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "n = 0\nn = n + 2 until (n*n).modulo(1000000) == 269696 \nprint n \n"} {"title": "Balanced brackets", "language": "Ruby 1.9", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "re = /\\A # beginning of string\n (? # begin capture group \n \\[ # literal [\n \\g* # zero or more \n \\] # literal ]\n )* # end group, zero or more such groups\n\\z/x # end of string\n\n10.times do |i|\n s = (%w{[ ]} * i).shuffle.join\n puts (s =~ re ? \" OK: \" : \"bad: \") + s\nend\n\n[\"[[]\", \"[]]\", \"a[ letters[-1] ].xyz[0]\"].each do |s|\n t = s.gsub(/[^\\[\\]]/, \"\")\n puts (t =~ re ? \" OK: \" : \"bad: \") + s\nend"} {"title": "Balanced ternary", "language": "Ruby", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "class BalancedTernary\n include Comparable\n def initialize(str = \"\")\n if str =~ /[^-+0]+/\n raise ArgumentError, \"invalid BalancedTernary number: #{str}\"\n end\n @digits = trim0(str)\n end\n \n I2BT = {0 => [\"0\",0], 1 => [\"+\",0], 2 => [\"-\",1]}\n def self.from_int(value)\n n = value.to_i\n digits = \"\"\n while n != 0\n quo, rem = n.divmod(3)\n bt, carry = I2BT[rem]\n digits = bt + digits\n n = quo + carry\n end\n new(digits)\n end\n \n BT2I = {\"-\" => -1, \"0\" => 0, \"+\" => 1}\n def to_int\n @digits.chars.inject(0) do |sum, char|\n sum = 3 * sum + BT2I[char]\n end\n end\n alias :to_i :to_int\n \n def to_s\n @digits.dup # String is mutable\n end\n alias :inspect :to_s\n \n def <=>(other)\n to_i <=> other.to_i\n end\n \n ADDITION_TABLE = {\n \"---\" => [\"-\",\"0\"], \"--0\" => [\"-\",\"+\"], \"--+\" => [\"0\",\"-\"],\n \"-0-\" => [\"-\",\"+\"], \"-00\" => [\"0\",\"-\"], \"-0+\" => [\"0\",\"0\"],\n \"-+-\" => [\"0\",\"-\"], \"-+0\" => [\"0\",\"0\"], \"-++\" => [\"0\",\"+\"],\n \"0--\" => [\"-\",\"+\"], \"0-0\" => [\"0\",\"-\"], \"0-+\" => [\"0\",\"0\"],\n \"00-\" => [\"0\",\"-\"], \"000\" => [\"0\",\"0\"], \"00+\" => [\"0\",\"+\"],\n \"0+-\" => [\"0\",\"0\"], \"0+0\" => [\"0\",\"+\"], \"0++\" => [\"+\",\"-\"],\n \"+--\" => [\"0\",\"-\"], \"+-0\" => [\"0\",\"0\"], \"+-+\" => [\"0\",\"+\"],\n \"+0-\" => [\"0\",\"0\"], \"+00\" => [\"0\",\"+\"], \"+0+\" => [\"+\",\"-\"],\n \"++-\" => [\"0\",\"+\"], \"++0\" => [\"+\",\"-\"], \"+++\" => [\"+\",\"0\"],\n }\n \n def +(other)\n maxl = [to_s.length, other.to_s.length].max\n a = pad0_reverse(to_s, maxl)\n b = pad0_reverse(other.to_s, maxl)\n carry = \"0\"\n sum = a.zip( b ).inject(\"\") do |sum, (c1, c2)|\n carry, digit = ADDITION_TABLE[carry + c1 + c2]\n sum = digit + sum\n end\n self.class.new(carry + sum)\n end\n \n MULTIPLICATION_TABLE = {\n \"-\" => \"+0-\",\n \"0\" => \"000\",\n \"+\" => \"-0+\",\n }\n \n def *(other)\n product = self.class.new\n other.to_s.each_char do |bdigit|\n row = to_s.tr(\"-0+\", MULTIPLICATION_TABLE[bdigit])\n product += self.class.new(row)\n product << 1\n end\n product >> 1\n end\n \n # negation\n def -@()\n self.class.new(@digits.tr('-+','+-'))\n end\n \n # subtraction\n def -(other)\n self + (-other)\n end\n \n # shift left\n def <<(count)\n @digits = trim0(@digits + \"0\"*count)\n self\n end\n \n # shift right\n def >>(count)\n @digits[-count..-1] = \"\" if count > 0\n @digits = trim0(@digits)\n self\n end\n \n private\n \n def trim0(str)\n str = str.sub(/^0+/, \"\")\n str = \"0\" if str.empty?\n str\n end\n \n def pad0_reverse(str, len)\n str.rjust(len, \"0\").reverse.chars\n end\nend\n\na = BalancedTernary.new(\"+-0++0+\")\nb = BalancedTernary.from_int(-436)\nc = BalancedTernary.new(\"+-++-\")\n\n%w[a b c a*(b-c)].each do |exp|\n val = eval(exp)\n puts \"%8s :%13s,%8d\" % [exp, val, val.to_i]\nend"} {"title": "Base64 decode data", "language": "Ruby", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "require 'base64'\n\nraku_example ='\nVG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2\n9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=\n'\nputs Base64.decode64 raku_example"} {"title": "Bell numbers", "language": "Ruby from D", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "def bellTriangle(n)\n tri = Array.new(n)\n for i in 0 .. n - 1 do\n tri[i] = Array.new(i)\n for j in 0 .. i - 1 do\n tri[i][j] = 0\n end\n end\n tri[1][0] = 1\n for i in 2 .. n - 1 do\n tri[i][0] = tri[i - 1][i - 2]\n for j in 1 .. i - 1 do\n tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]\n end\n end\n return tri\nend\n\ndef main\n bt = bellTriangle(51)\n puts \"First fifteen and fiftieth Bell numbers:\"\n for i in 1 .. 15 do\n puts \"%2d: %d\" % [i, bt[i][0]]\n end\n puts \"50: %d\" % [bt[50][0]]\n puts\n\n puts \"The first ten rows of Bell's triangle:\"\n for i in 1 .. 10 do\n puts bt[i].inspect\n end\nend\n\nmain()"} {"title": "Benford's law", "language": "Ruby from Python", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "EXPECTED = (1..9).map{|d| Math.log10(1+1.0/d)}\n\ndef fib(n)\n a,b = 0,1\n n.times.map{ret, a, b = a, b, a+b; ret}\nend\n\n# powers of 3 as a test sequence\ndef power_of_threes(n)\n n.times.map{|k| 3**k}\nend\n\ndef heads(s)\n s.map{|a| a.to_s[0].to_i}\nend\n\ndef show_dist(title, s)\n s = heads(s)\n c = Array.new(10, 0)\n s.each{|x| c[x] += 1}\n size = s.size.to_f\n res = (1..9).map{|d| c[d]/size}\n puts \"\\n %s Benfords deviation\" % title\n res.zip(EXPECTED).each.with_index(1) do |(r, e), i|\n puts \"%2d: %5.1f%% %5.1f%% %5.1f%%\" % [i, r*100, e*100, (r - e).abs*100]\n end\nend\n\ndef random(n)\n n.times.map{rand(1..n)}\nend\n\nshow_dist(\"fibbed\", fib(1000))\nshow_dist(\"threes\", power_of_threes(1000))\n\n# just to show that not all kind-of-random sets behave like that\nshow_dist(\"random\", random(10000))"} {"title": "Best shuffle", "language": "Ruby from Raku", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "def best_shuffle(s)\n # Fill _pos_ with positions in the order\n # that we want to fill them.\n pos = []\n # g[\"a\"] = [2, 4] implies that s[2] == s[4] == \"a\"\n g = s.length.times.group_by { |i| s[i] }\n \n # k sorts letters from low to high count\n k = g.sort_by { |k, v| v.length }.map { |k, v| k }\n \n until g.empty?\n k.each do |letter|\n g[letter] or next\n pos.push(g[letter].pop)\n g[letter].empty? and g.delete letter\n end\n end\n \n # Now fill in _new_ with _letters_ according to each position\n # in _pos_, but skip ahead in _letters_ if we can avoid\n # matching characters that way.\n letters = s.dup\n new = \"?\" * s.length\n until letters.empty?\n i, p = 0, pos.pop\n i += 1 while letters[i] == s[p] and i < (letters.length - 1)\n new[p] = letters.slice! i\n end\n \n score = new.chars.zip(s.chars).count { |c, d| c == d }\n [new, score]\nend\n\n%w(abracadabra seesaw elk grrrrrr up a).each do |word|\n puts \"%s, %s, (%d)\" % [word, *best_shuffle(word)]\nend"} {"title": "Bin given limits", "language": "Ruby", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "Test = Struct.new(:limits, :data)\ntests = Test.new( [23, 37, 43, 53, 67, 83],\n [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]),\n Test.new( [14, 18, 249, 312, 389, 392, 513, 591, 634, 720],\n [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749])\n\ndef bin(limits, data)\n data.map{|d| limits.bsearch{|limit| limit > d} }.tally\nend\n\ndef present_bins(limits, bins)\n ranges = ([nil]+limits+[nil]).each_cons(2).map{|low, high| Range.new(low, high, true) }\n ranges.each{|range| puts \"#{range.to_s.ljust(12)} #{bins[range.end].to_i}\"}\nend\n\ntests.each do |test|\n present_bins(test.limits, bin(test.limits, test.data))\n puts\nend\n"} {"title": "Bioinformatics/Sequence mutation", "language": "Ruby", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "class DNA_Seq\n attr_accessor :seq\n \n def initialize(bases: %i[A C G T] , size: 0)\n @bases = bases\n @seq = Array.new(size){ bases.sample }\n end\n \n def mutate(n = 10)\n n.times{|n| method([:s, :d, :i].sample).call}\n end\n \n def to_s(n = 50)\n just_size = @seq.size / n\n (0...@seq.size).step(n).map{|from| \"#{from.to_s.rjust(just_size)} \" + @seq[from, n].join}.join(\"\\n\") +\n \"\\nTotal #{seq.size}: #{@seq.tally.sort.to_h.inspect}\\n\\n\"\n end\n\n def s = @seq[rand_index]= @bases.sample \n def d = @seq.delete_at(rand_index)\n def i = @seq.insert(rand_index, @bases.sample )\n alias :swap :s \n alias :delete :d\n alias :insert :i\n \n private\n def rand_index = rand( @seq.size )\nend\n\nputs test = DNA_Seq.new(size: 200)\ntest.mutate\nputs test\ntest.delete\nputs test\n"} {"title": "Bioinformatics/base count", "language": "Ruby", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "dna = < 0 do\n n,ng = n.divmod(58)\n res << G[ng]\nend\nputs res.reverse\n"} {"title": "Bitwise IO", "language": "Ruby 1.8.7", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "def crunch(ascii)\n bitstring = ascii.bytes.collect {|b| \"%07b\" % b}.join\n [bitstring].pack(\"B*\")\nend\n\ndef expand(binary)\n bitstring = binary.unpack(\"B*\")[0]\n bitstring.scan(/[01]{7}/).collect {|b| b.to_i(2).chr}.join\nend\n\noriginal = \"This is an ascii string that will be crunched, written, read and expanded.\"\nputs \"my ascii string is #{original.length} bytes\"\n\nfilename = \"crunched.out\"\n\n# write the compressed data\nFile.open(filename, \"w\") do |fh|\n fh.binmode\n fh.print crunch(original)\nend\n\nfilesize = File.size(filename)\nputs \"the file containing the crunched text is #{filesize} bytes\"\n\n# read and expand\nexpanded = File.open(filename, \"r\") do |fh| \n fh.binmode\n expand(fh.read)\nend\n\nif original == expanded\n puts \"success\"\nelse\n puts \"fail!\"\nend"} {"title": "Box the compass", "language": "Ruby", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "Headings = %w(north east south west north).each_cons(2).flat_map do |a, b|\n [a,\n \"#{a} by #{b}\",\n \"#{a}-#{a}#{b}\",\n \"#{a}#{b} by #{a}\",\n \"#{a}#{b}\", \n \"#{a}#{b} by #{b}\",\n \"#{b}-#{a}#{b}\",\n \"#{b} by #{a}\"]\nend\nHeadings.prepend nil\n\ndef heading(degrees)\n i = degrees.quo(360).*(32).round.%(32).+(1)\n [i, Headings[i]]\nend\n\n# an array of angles, in degrees\nangles = (0..32).map { |i| i * 11.25 + [0, 5.62, -5.62][i % 3] }\n\nangles.each do |degrees|\n index, name = heading degrees\n printf \"%2d %20s %6.2f\\n\", index, name.center(20), degrees\nend"} {"title": "Brazilian numbers", "language": "Ruby from C++", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "def sameDigits(n,b)\n f = n % b\n while (n /= b) > 0 do\n if n % b != f then\n return false\n end\n end\n return true\nend\n\ndef isBrazilian(n)\n if n < 7 then\n return false\n end\n if n % 2 == 0 then\n return true\n end\n for b in 2 .. n - 2 do\n if sameDigits(n, b) then\n return true\n end\n end\n return false\nend\n\ndef isPrime(n)\n if n < 2 then\n return false\n end\n if n % 2 == 0 then\n return n == 2\n end\n if n % 3 == 0 then\n return n == 3\n end\n d = 5\n while d * d <= n do\n if n % d == 0 then\n return false\n end\n d = d + 2\n\n if n % d == 0 then\n return false\n end\n d = d + 4\n end\n return true\nend\n\ndef main\n for kind in [\"\", \"odd \", \"prime \"] do\n quiet = false\n bigLim = 99999\n limit = 20\n puts \"First %d %sBrazilian numbers:\" % [limit, kind]\n c = 0\n n = 7\n while c < bigLim do\n if isBrazilian(n) then\n if not quiet then\n print \"%d \" % [n]\n end\n c = c + 1\n if c == limit then\n puts\n puts\n quiet = true\n end\n end\n if quiet and kind != \"\" then\n next\n end\n if kind == \"\" then\n n = n + 1\n elsif kind == \"odd \" then\n n = n + 2\n elsif kind == \"prime \" then\n loop do\n n = n + 2\n if isPrime(n) then\n break\n end\n end\n else\n raise \"Unexpected\"\n end\n end\n if kind == \"\" then\n puts \"The %dth Brazillian number is: %d\" % [bigLim + 1, n]\n puts\n end\n end\nend\n\nmain()"} {"title": "Break OO privacy", "language": "Ruby", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": "class Example\n def initialize\n @private_data = \"nothing\" # instance variables are always private\n end\n private\n def hidden_method\n \"secret\"\n end\nend\nexample = Example.new\np example.private_methods(false) # => [:hidden_method]\n#p example.hidden_method # => NoMethodError: private method `name' called for #\np example.send(:hidden_method) # => \"secret\"\np example.instance_variables # => [:@private_data]\np example.instance_variable_get :@private_data # => \"nothing\"\np example.instance_variable_set :@private_data, 42 # => 42\np example.instance_variable_get :@private_data # => 42\n"} {"title": "Burrows\u2013Wheeler transform", "language": "Ruby from C#", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "STX = \"\\u0002\"\nETX = \"\\u0003\"\n\ndef bwt(s)\n for c in s.split('')\n if c == STX or c == ETX then\n raise ArgumentError.new(\"Input can't contain STX or ETX\")\n end\n end\n\n ss = (\"%s%s%s\" % [STX, s, ETX]).split('')\n table = []\n for i in 0 .. ss.length - 1\n table.append(ss.join)\n ss = ss.rotate(-1)\n end\n\n table = table.sort\n return table.map{ |e| e[-1] }.join\nend\n\ndef ibwt(r)\n len = r.length\n table = [\"\"] * len\n for i in 0 .. len - 1\n for j in 0 .. len - 1\n table[j] = r[j] + table[j]\n end\n table = table.sort\n end\n for row in table\n if row[-1] == ETX then\n return row[1 .. -2]\n end\n end\n return \"\"\nend\n\ndef makePrintable(s)\n s = s.gsub(STX, \"^\")\n return s.gsub(ETX, \"|\")\nend\n\ndef main\n tests = [\n \"banana\",\n \"appellee\",\n \"dogwood\",\n \"TO BE OR NOT TO BE OR WANT TO BE OR NOT?\",\n \"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\",\n \"\\u0002ABC\\u0003\"\n ]\n for test in tests\n print makePrintable(test), \"\\n\"\n print \" --> \"\n\n begin\n t = bwt(test)\n print makePrintable(t), \"\\n\"\n\n r = ibwt(t)\n print \" --> \", r, \"\\n\\n\"\n rescue ArgumentError => e\n print e.message, \"\\n\"\n print \" -->\\n\\n\"\n end\n end\nend\n\nmain()"} {"title": "CSV data manipulation", "language": "Ruby", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "require 'csv'\n# read:\nar = CSV.table(\"test.csv\").to_a #table method assumes headers and converts numbers if possible.\n\n# manipulate:\nar.first << \"SUM\"\nar[1..-1].each{|row| row << row.sum}\n\n# write:\nCSV.open(\"out.csv\", 'w') do |csv|\n ar.each{|line| csv << line}\nend"} {"title": "CSV to HTML translation", "language": "Ruby", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "require 'cgi'\n\nputs ''\n\ndef row2html str, wrap = \"td\"\n \"\" +\n str.split(\",\").map { |cell| \"<#{wrap}>#{CGI.escapeHTML cell}\" }.join +\n \"\"\nend\n\nputs row2html gets.chomp, \"th\" if ARGV.delete \"header\"\n\nwhile str = gets\n puts row2html str.chomp\nend\n\nputs \"
\""} {"title": "Calculating the value of e", "language": "Ruby from C", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "fact = 1\ne = 2\ne0 = 0\nn = 2\n\nuntil (e - e0).abs < Float::EPSILON do\n e0 = e\n fact *= n\n n += 1\n e += 1.0 / fact\nend\n\nputs e\n"} {"title": "Calkin-Wilf sequence", "language": "Ruby from Python", "task": "The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once. \n\nIt can be calculated recursively as follows:\n\n {{math|a1}} = {{math|1}} \n {{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1 \n\n\n;Task part 1:\n* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.\n\nTo avoid floating point error, you may want to use a rational number data type.\n\n\nIt is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. \nIt only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:\n\n {{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}} \n\n\n;Example:\nThe fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''', \nwhich means '''9/4''' appears as the '''35th''' term of the sequence.\n\n\n;Task part 2:\n* Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence.\n\n\n;See also:\n* Wikipedia entry: Calkin-Wilf tree\n* [[Continued fraction]]\n* [[Continued fraction/Arithmetic/Construct from rational number]]\n\n", "solution": "cw = Enumerator.new do |y|\n y << a = 1.to_r\n loop { y << a = 1/(2*a.floor + 1 - a) }\nend\n\ndef term_num(rat)\n num, den, res, pwr, dig = rat.numerator, rat.denominator, 0, 0, 1\n while den > 0 \n num, (digit, den) = den, num.divmod(den) \n digit.times do\n res |= dig << pwr\n pwr += 1\n end\n dig ^= 1\n end\n res\nend\n\nputs cw.take(20).join(\", \")\nputs term_num (83116/51639r)\n"} {"title": "Call a function", "language": "Ruby", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "# return value substance\ni = 3\np 1 + i #=> 4 1.+(i)\np i < 5 #=> true i.<(5)\np 2 ** i #=> 8 2.**(i)\np -i #=> -3 i.-@()\na = [1,2,3]\np a[0] #=> 1 a.[](0)\na[2] = \"0\" # a.[]=(2,\"0\")\np a << 5 #=> [1, 2, \"0\", 5] a.<<(5)\np a & [4,2] #=> [2] a.&([4,2])\np \"abcde\"[1..3] #=> \"bcd\" \"abcde\".[](1..3)\np \"%2d %4s\" % [1,\"xyz\"] #=> \" 1 xyz\" \"%2d %4s\".%([1,\"xyz\"])"} {"title": "Canonicalize CIDR", "language": "Ruby from Raku", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "#!/usr/bin/env ruby\n\n# canonicalize a CIDR block: make sure none of the host bits are set\nif ARGV.length == 0 then\n ARGV = $stdin.readlines.map(&:chomp)\nend\n\nARGV.each do |cidr|\n\n # dotted-decimal / bits in network part\n dotted, size_str = cidr.split('/')\n size = size_str.to_i\n\n # get IP as binary string\n binary = dotted.split('.').map { |o| \"%08b\" % o }.join\n\n # Replace the host part with all zeroes\n binary[size .. -1] = '0' * (32 - size)\n\n # Convert back to dotted-decimal\n canon = binary.chars.each_slice(8).map { |a| a.join.to_i(2) }.join('.')\n\n # And output\n puts \"#{canon}/#{size}\"\nend"} {"title": "Cantor set", "language": "Ruby", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "lines = 5\n\n(0..lines).each do |exp|\n seg_size = 3**(lines-exp-1)\n chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? \" \" : \"\u2588\"}\n puts chars.map{ |c| c * seg_size }.join\nend\n"} {"title": "Cartesian product of two or more lists", "language": "Ruby", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "p [1, 2].product([3, 4]) \np [3, 4].product([1, 2])\np [1, 2].product([])\np [].product([1, 2]) \np [1776, 1789].product([7, 12], [4, 14, 23], [0, 1])\np [1, 2, 3].product([30], [500, 100]) \np [1, 2, 3].product([], [500, 100]) \n"} {"title": "Casting out nines", "language": "Ruby from C", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "N = 2\nbase = 10\nc1 = 0\nc2 = 0\n\nfor k in 1 .. (base ** N) - 1\n c1 = c1 + 1\n if k % (base - 1) == (k * k) % (base - 1) then\n c2 = c2 + 1\n print \"%d \" % [k]\n end\nend\n\nputs\nprint \"Trying %d numbers instead of %d numbers saves %f%%\" % [c2, c1, 100.0 - 100.0 * c2 / c1]"} {"title": "Catalan numbers/Pascal's triangle", "language": "Ruby", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "def catalan(num)\n t = [0, 1] #grows as needed\n (1..num).map do |i|\n i.downto(1){|j| t[j] += t[j-1]}\n t[i+1] = t[i]\n (i+1).downto(1) {|j| t[j] += t[j-1]}\n t[i+1] - t[i]\n end\nend\n\np catalan(15)"} {"title": "Catamorphism", "language": "Ruby", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "p row = [1]\n10.times{p row = row.each_cons(2).inject([1,1]){|ar,(a,b)| ar.insert(-2, a+b)} }\n\n# [1]\n# [1, 1]\n# [1, 2, 1]\n# [1, 3, 3, 1]\n# [1, 4, 6, 4, 1]\n# [1, 5, 10, 10, 5, 1]\n# [1, 6, 15, 20, 15, 6, 1]\n# etc\n"} {"title": "Chaocipher", "language": "Ruby", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "txt = \"WELLDONEISBETTERTHANWELLSAID\"\n@left = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\".chars\n@right = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\".chars\n\ndef encrypt(char)\n coded_char = @left[@right.index(char)]\n\n @left.rotate!(@left.index(coded_char))\n part = @left.slice!(1,13).rotate\n @left.insert(1, *part)\n\n @right.rotate!(@right.index(char)+1)\n part = @right.slice!(2,12).rotate\n @right.insert(2, *part)\n \n @left[0]\nend\n\nputs txt.each_char.map{|c| encrypt(c) }.join \n"} {"title": "Check input device is a terminal", "language": "Ruby", "task": "Demonstrate how to check whether the input device is a terminal or not.\n\n\n;Related task:\n* [[Check output device is a terminal]]\n\n", "solution": "File.new(\"testfile\").isatty #=> false\nFile.new(\"/dev/tty\").isatty #=> true"} {"title": "Check output device is a terminal", "language": "Ruby", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "f = File.open(\"test.txt\")\np f.isatty # => false\np STDOUT.isatty # => true\n"} {"title": "Cheryl's birthday", "language": "Ruby from C#", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "dates = [\n [\"May\", 15],\n [\"May\", 16],\n [\"May\", 19],\n [\"June\", 17],\n [\"June\", 18],\n [\"July\", 14],\n [\"July\", 16],\n [\"August\", 14],\n [\"August\", 15],\n [\"August\", 17],\n]\n\nprint dates.length, \" remaining\\n\"\n\n# the month cannot have a unique day\nuniqueMonths = dates.group_by { |m,d| d }\n .select { |k,v| v.size == 1 }\n .map { |k,v| v.flatten }\n .map { |m,d| m }\ndates.delete_if { |m,d| uniqueMonths.include? m }\nprint dates.length, \" remaining\\n\"\n\n# the day must be unique\ndates = dates .group_by { |m,d| d }\n .select { |k,v| v.size == 1 }\n .map { |k,v| v.flatten }\nprint dates.length, \" remaining\\n\"\n\n# the month must now be unique\ndates = dates .group_by { |m,d| m }\n .select { |k,v| v.size == 1 }\n .map { |k,v| v }\n .flatten\nprint dates"} {"title": "Chinese remainder theorem", "language": "Ruby", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "def extended_gcd(a, b)\n last_remainder, remainder = a.abs, b.abs\n x, last_x = 0, 1\n while remainder != 0\n last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)\n x, last_x = last_x - quotient*x, x\n end\n return last_remainder, last_x * (a < 0 ? -1 : 1)\nend\n\ndef invmod(e, et)\n g, x = extended_gcd(e, et)\n if g != 1\n raise 'Multiplicative inverse modulo does not exist!'\n end\n x % et\nend\n\ndef chinese_remainder(mods, remainders)\n max = mods.inject( :* ) # product of all moduli\n series = remainders.zip(mods).map{ |r,m| (r * max * invmod(max/m, m) / m) }\n series.inject( :+ ) % max \nend\n\np chinese_remainder([3,5,7], [2,3,2]) #=> 23\np chinese_remainder([17353461355013928499, 3882485124428619605195281, 13563122655762143587], [7631415079307304117, 1248561880341424820456626, 2756437267211517231]) #=> 937307771161836294247413550632295202816\np chinese_remainder([10,4,9], [11,22,19]) #=> nil\n"} {"title": "Chinese zodiac", "language": "Ruby", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "# encoding: utf-8\npinyin = {\n '\u7532' => 'ji\u0103',\n '\u4e59' => 'y\u012d',\n '\u4e19' => 'b\u012dng',\n '\u4e01' => 'd\u012bng',\n '\u620a' => 'w\u00f9',\n '\u5df1' => 'j\u012d',\n '\u5e9a' => 'g\u0113ng',\n '\u8f9b' => 'x\u012bn',\n '\u58ec' => 'r\u00e9n',\n '\u7678' => 'g\u016di',\n\n '\u5b50' => 'z\u012d',\n '\u4e11' => 'ch\u014fu',\n '\u5bc5' => 'y\u00edn',\n '\u536f' => 'm\u0103o',\n '\u8fb0' => 'ch\u00e9n',\n '\u5df3' => 's\u00ec',\n '\u5348' => 'w\u016d',\n '\u672a' => 'w\u00e8i',\n '\u7533' => 'sh\u0113n',\n '\u9149' => 'y\u014fu',\n '\u620c' => 'x\u016b',\n '\u4ea5' => 'h\u00e0i'\n}\ncelestial = %w(\u7532 \u4e59 \u4e19 \u4e01 \u620a \u5df1 \u5e9a \u8f9b \u58ec \u7678)\nterrestrial = %w(\u5b50 \u4e11 \u5bc5 \u536f \u8fb0 \u5df3 \u5348 \u672a \u7533 \u9149 \u620c \u4ea5)\nanimals = %w(Rat Ox Tiger Rabbit Dragon Snake\n Horse Goat Monkey Rooster Dog Pig)\nelements = %w(Wood Fire Earth Metal Water)\naspects = %w(yang yin)\n\nBASE = 4\n\nargs = if !ARGV.empty?\n ARGV\n else\n [Time.new.year]\n end\n\nargs.each do |arg|\n ce_year = Integer(arg)\n print \"#{ce_year}: \" if ARGV.length > 1\n cycle_year = ce_year - BASE\n\n stem_number = cycle_year % 10\n stem_han = celestial[stem_number]\n stem_pinyin = pinyin[stem_han]\n\n element_number = stem_number / 2\n element = elements[element_number]\n\n branch_number = cycle_year % 12\n branch_han = terrestrial[branch_number]\n branch_pinyin = pinyin[branch_han]\n animal = animals[branch_number]\n\n aspect_number = cycle_year % 2\n aspect = aspects[aspect_number]\n\n index = cycle_year % 60 + 1\n\n print stem_han, branch_han\n puts \" (#{stem_pinyin}-#{branch_pinyin}, #{element} #{animal}; #{aspect} - year #{index} of the cycle)\"\nend"} {"title": "Church numerals", "language": "Ruby from Raku", "task": "In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n\n", "solution": "def zero(f)\n return lambda {|x| x}\nend\nZero = lambda { |f| zero(f) }\n \ndef succ(n)\n return lambda { |f| lambda { |x| f.(n.(f).(x)) } }\nend\n \nThree = succ(succ(succ(Zero)))\n \ndef add(n, m)\n return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } }\nend\n \ndef mult(n, m)\n return lambda { |f| lambda { |x| m.(n.(f)).(x) } }\nend\n \ndef power(b, e)\n return e.(b)\nend\n \ndef int_from_couch(f)\n countup = lambda { |i| i+1 }\n f.(countup).(0)\nend\n \ndef couch_from_int(x)\n countdown = lambda { |i|\n case i \n when 0 then Zero \n else succ(countdown.(i-1))\n end\n }\n countdown.(x)\nend\n \nFour = couch_from_int(4)\n \nputs [ add(Three, Four),\n mult(Three, Four),\n power(Three, Four),\n power(Four, Three) ].map {|f| int_from_couch(f) }\n"} {"title": "Circles of given radius through two points", "language": "Ruby from Python", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "Pt = Struct.new(:x, :y)\nCircle = Struct.new(:x, :y, :r)\n\ndef circles_from(pt1, pt2, r)\n raise ArgumentError, \"Infinite number of circles, points coincide.\" if pt1 == pt2 && r > 0\n # handle single point and r == 0\n return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0\n dx, dy = pt2.x - pt1.x, pt2.y - pt1.y\n # distance between points\n q = Math.hypot(dx, dy)\n # Also catches pt1 != pt2 && r == 0\n raise ArgumentError, \"Distance of points > diameter.\" if q > 2.0*r\n # halfway point\n x3, y3 = (pt1.x + pt2.x)/2.0, (pt1.y + pt2.y)/2.0\n d = (r**2 - (q/2)**2)**0.5\n [Circle.new(x3 - d*dy/q, y3 + d*dx/q, r),\n Circle.new(x3 + d*dy/q, y3 - d*dx/q, r)].uniq\nend\n\n# Demo:\nar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0],\n [Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0],\n [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0],\n [Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5],\n [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]]\n\nar.each do |p1, p2, r|\n print \"Given points:\\n #{p1.values},\\n #{p2.values}\\n and radius #{r}\\n\"\n begin\n circles = circles_from(p1, p2, r)\n puts \"You can construct the following circles:\"\n circles.each{|c| puts \" #{c}\"}\n rescue ArgumentError => e\n puts e\n end\n puts\nend"} {"title": "Cistercian numerals", "language": "Ruby from Lua", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "def initN\n n = Array.new(15){Array.new(11, ' ')}\n for i in 1..15\n n[i - 1][5] = 'x'\n end\n return n\nend\n\ndef horiz(n, c1, c2, r)\n for c in c1..c2\n n[r][c] = 'x'\n end\nend\n\ndef verti(n, r1, r2, c)\n for r in r1..r2\n n[r][c] = 'x'\n end\nend\n\ndef diagd(n, c1, c2, r)\n for c in c1..c2\n n[r+c-c1][c] = 'x'\n end\nend\n\ndef diagu(n, c1, c2, r)\n for c in c1..c2\n n[r-c+c1][c] = 'x'\n end\nend\n\ndef initDraw\n draw = []\n\n draw[1] = lambda do |n| horiz(n, 6, 10, 0) end\n draw[2] = lambda do |n| horiz(n, 6, 10, 4) end\n draw[3] = lambda do |n| diagd(n, 6, 10, 0) end\n draw[4] = lambda do |n| diagu(n, 6, 10, 4) end\n draw[5] = lambda do |n|\n draw[1].call(n)\n draw[4].call(n)\n end\n draw[6] = lambda do |n| verti(n, 0, 4, 10) end\n draw[7] = lambda do |n|\n draw[1].call(n)\n draw[6].call(n)\n end\n draw[8] = lambda do |n|\n draw[2].call(n)\n draw[6].call(n)\n end\n draw[9] = lambda do |n|\n draw[1].call(n)\n draw[8].call(n)\n end\n\n draw[10] = lambda do |n| horiz(n, 0, 4, 0) end\n draw[20] = lambda do |n| horiz(n, 0, 4, 4) end\n draw[30] = lambda do |n| diagu(n, 0, 4, 4) end\n draw[40] = lambda do |n| diagd(n, 0, 4, 0) end\n draw[50] = lambda do |n|\n draw[10].call(n)\n draw[40].call(n)\n end\n draw[60] = lambda do |n| verti(n, 0, 4, 0) end\n draw[70] = lambda do |n|\n draw[10].call(n)\n draw[60].call(n)\n end\n draw[80] = lambda do |n|\n draw[20].call(n)\n draw[60].call(n)\n end\n draw[90] = lambda do |n|\n draw[10].call(n)\n draw[80].call(n)\n end\n\n draw[100] = lambda do |n| horiz(n, 6, 10, 14) end\n draw[200] = lambda do |n| horiz(n, 6, 10, 10) end\n draw[300] = lambda do |n| diagu(n, 6, 10, 14) end\n draw[400] = lambda do |n| diagd(n, 6, 10, 10) end\n draw[500] = lambda do |n|\n draw[100].call(n)\n draw[400].call(n)\n end\n draw[600] = lambda do |n| verti(n, 10, 14, 10) end\n draw[700] = lambda do |n|\n draw[100].call(n)\n draw[600].call(n)\n end\n draw[800] = lambda do |n|\n draw[200].call(n)\n draw[600].call(n)\n end\n draw[900] = lambda do |n|\n draw[100].call(n)\n draw[800].call(n)\n end\n\n draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end\n draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end\n draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end\n draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end\n draw[5000] = lambda do |n|\n draw[1000].call(n)\n draw[4000].call(n)\n end\n draw[6000] = lambda do |n| verti(n, 10, 14, 0) end\n draw[7000] = lambda do |n|\n draw[1000].call(n)\n draw[6000].call(n)\n end\n draw[8000] = lambda do |n|\n draw[2000].call(n)\n draw[6000].call(n)\n end\n draw[9000] = lambda do |n|\n draw[1000].call(n)\n draw[8000].call(n)\n end\n\n return draw\nend\n\ndef printNumeral(n)\n for a in n\n for b in a\n print b\n end\n print \"\\n\"\n end\n print \"\\n\"\nend\n\ndraw = initDraw()\nfor number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]\n n = initN()\n print number, \":\\n\"\n\n thousands = (number / 1000).floor\n number = number % 1000\n\n hundreds = (number / 100).floor\n number = number % 100\n\n tens = (number / 10).floor\n ones = number % 10\n\n if thousands > 0 then\n draw[thousands * 1000].call(n)\n end\n if hundreds > 0 then\n draw[hundreds * 100].call(n)\n end\n if tens > 0 then\n draw[tens * 10].call(n)\n end\n if ones > 0 then\n draw[ones].call(n)\n end\n printNumeral(n)\nend"} {"title": "Closures/Value capture", "language": "Ruby", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda\np procs[7].call # => 49"} {"title": "Colorful numbers", "language": "Ruby", "task": "A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.\n\n\n;E.G.\n\n24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144\n\nThe product '''6''' is repeated.\n\n\nSingle digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\n\n;Task\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\n\n;Stretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of '''all''' colorful numbers.\n\n\n''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''\n\n", "solution": "def colorful?(ar)\n products = []\n (1..ar.size).all? do |chunk_size|\n ar.each_cons(chunk_size) do |chunk|\n product = chunk.inject(&:*)\n return false if products.include?(product)\n products << product\n end\n end\nend\n\nbelow100 = (0..100).select{|n| colorful?(n.digits)}\nputs \"The colorful numbers less than 100 are:\", below100.join(\" \"), \"\"\nputs \"Largest colorful number: #{(98765432.downto(1).detect{|n| colorful?(n.digits) })}\", \"\"\n\ntotal = 0\n(1..8).each do |numdigs|\n digits = (numdigs == 1 ? (0..9).to_a : (2..9).to_a)\n count = digits.permutation(numdigs).count{|perm| colorful?(perm)}\n puts \"#{numdigs} digit colorful numbers count: #{count}\"\n total += count\nend\n\nputs \"\\nTotal colorful numbers: #{total}\"\n"} {"title": "Comma quibbling", "language": "Ruby from Raku", "task": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "def comma_quibbling(a)\n %w<{ }>.join(a.length < 2 ? a.first :\n \"#{a[0..-2].join(', ')} and #{a[-1]}\")\nend\n\n[[], %w, %w, %w].each do |a|\n puts comma_quibbling(a)\nend"} {"title": "Compare a list of strings", "language": "Ruby", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "strings.all?{|str| str == strings.first} # all equal?\nstrings.each_cons(2).all?{|str1, str2| str1 < str2} # ascending?"} {"title": "Composite numbers k with no single digit factors whose factors are all substrings of k", "language": "Ruby", "task": "Find the composite numbers '''k''' in base 10, that have no single digit prime factors and whose prime factors are all a substring of '''k'''.\n\n\n;Task\n\n* Find and show here, on this page, the first ten elements of the sequence.\n\n\n\n;Stretch\n\n* Find and show the next ten elements.\n\n\n\n\n", "solution": "require 'prime'\n\ngenerator2357 = Enumerator.new do |y|\n gen23 = Prime::Generator23.new\n gen23.each {|n| y << n unless (n%5 == 0 || n%7 == 0) }\nend\n\nres = generator2357.lazy.select do |n|\n primes, exp = n.prime_division.transpose\n next if exp.sum < 2 #exclude primes\n s = n.to_s\n primes.all?{|pr| s.match?(-pr.to_s) }\nend\n\nres.take(10).each{|n| puts n}"} {"title": "Conjugate transpose", "language": "Ruby 2.0", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "require 'matrix'\n\n# Start with some matrix.\ni = Complex::I\nmatrix = Matrix[[i, 0, 0],\n [0, i, 0],\n [0, 0, i]]\n\n# Find the conjugate transpose.\n# Matrix#conjugate appeared in Ruby 1.9.2.\nconjt = matrix.conj.t # aliases for matrix.conjugate.tranpose\nprint 'conjugate tranpose: '; puts conjt\n\nif matrix.square?\n # These predicates appeared in Ruby 1.9.3.\n print 'Hermitian? '; puts matrix.hermitian?\n print ' normal? '; puts matrix.normal?\n print ' unitary? '; puts matrix.unitary?\nelse\n # Matrix is not square. These predicates would\n # raise ExceptionForMatrix::ErrDimensionMismatch.\n print 'Hermitian? false'\n print ' normal? false'\n print ' unitary? false'\nend"} {"title": "Continued fraction", "language": "Ruby", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "require 'bigdecimal'\n\n# square root of 2\nsqrt2 = Object.new\ndef sqrt2.a(n); n == 1 ? 1 : 2; end\ndef sqrt2.b(n); 1; end\n\n# Napier's constant\nnapier = Object.new\ndef napier.a(n); n == 1 ? 2 : n - 1; end\ndef napier.b(n); n == 1 ? 1 : n - 1; end\n\npi = Object.new\ndef pi.a(n); n == 1 ? 3 : 6; end\ndef pi.b(n); (2*n - 1)**2; end\n\n# Estimates the value of a continued fraction _cfrac_, to _prec_\n# decimal digits of precision. Returns a BigDecimal. _cfrac_ must\n# respond to _cfrac.a(n)_ and _cfrac.b(n)_ for integer _n_ >= 1.\ndef estimate(cfrac, prec)\n last_result = nil\n terms = prec\n\n loop do\n # Estimate continued fraction for _n_ from 1 to _terms_.\n result = cfrac.a(terms)\n (terms - 1).downto(1) do |n|\n a = BigDecimal cfrac.a(n)\n b = BigDecimal cfrac.b(n)\n digits = [b.div(result, 1).exponent + prec, 1].max\n result = a + b.div(result, digits)\n end\n result = result.round(prec)\n\n if result == last_result\n return result\n else\n # Double _terms_ and try again.\n last_result = result\n terms *= 2\n end\n end\nend\n\nputs estimate(sqrt2, 50).to_s('F')\nputs estimate(napier, 50).to_s('F')\nputs estimate(pi, 10).to_s('F')"} {"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "Ruby", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "[[1,2], [3,1], [23,8], [13,11], [22,7], [-151,77]].each do |n1,n2|\n print \"%10s : \" % \"#{n1} / #{n2}\"\n r2cf(n1,n2) {|n| print \"#{n} \"}\n puts\nend"} {"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "Ruby", "task": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix}\nI may perform perform the following operations:\n:Input the next term of N1\n:Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \\frac{a}{b} and \\frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \\infty.\n\nWhen I input a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a + a_1 * t & a_1 \\\\\n b + b_1 * t & b_1 \n\\end{bmatrix}\n\nWhen I output a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} b_1 & b \\\\\n a_1 - b_1 * t & a - b * t \n\\end{bmatrix}\n\nWhen I need a term t but there are no more my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a_1 & a_1 \\\\\n b_1 & b_1 \n\\end{bmatrix}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n:[1;5,2] + 1/2\n:[3;7] + 1/2 \n:[3;7] divided by 4\nUsing a generator for \\sqrt{2} (e.g., from [[Continued fraction]]) calculate \\frac{1}{\\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.\n\nThe first step in implementing [[Arithmetic-geometric mean]] is to calculate \\frac{1 + \\frac{1}{\\sqrt{2}}}{2} do this now to cross the starting line and begin the race.\n\n", "solution": "# I define a class to implement baby NG\nclass NG\n def initialize(a1, a, b1, b)\n @a1, @a, @b1, @b = a1, a, b1, b\n end\n def ingress(n)\n @a, @a1 = @a1, @a + @a1 * n\n @b, @b1 = @b1, @b + @b1 * n\n end\n def needterm?\n return true if @b == 0 or @b1 == 0\n return true unless @a/@b == @a1/@b1\n false\n end\n def egress\n n = @a / @b\n @a, @b = @b, @a - @b * n\n @a1, @b1 = @b1, @a1 - @b1 * n\n n\n end\n def egress_done\n @a, @b = @a1, @b1 if needterm?\n egress\n end\n def done?\n @b == 0 and @b1 == 0\n end\nend"} {"title": "Convert decimal number to rational", "language": "Ruby 1.9+", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": "> '0.9054054 0.518518 0.75'.split.each { |d| puts \"%s %s\" % [d, Rational(d)] }\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n=> [\"0.9054054\", \"0.518518\", \"0.75\"]"} {"title": "Convert decimal number to rational", "language": "Ruby 2.1.0+", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": "A suffix for integer and float literals was introduced: \n\n\n2.1.0p0 :001 > 0.9054054r\n => (4527027/5000000) \n2.1.0p0 :002 > 0.518518r\n => (259259/500000) \n2.1.0p0 :003 > 0.75r\n => (3/4) \n\n\n"} {"title": "Convert seconds to compound duration", "language": "Ruby", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "MINUTE = 60\nHOUR = MINUTE*60\nDAY = HOUR*24\nWEEK = DAY*7\n\ndef sec_to_str(sec)\n w, rem = sec.divmod(WEEK)\n d, rem = rem.divmod(DAY)\n h, rem = rem.divmod(HOUR)\n m, s = rem.divmod(MINUTE)\n units = [\"#{w} wk\", \"#{d} d\", \"#{h} h\", \"#{m} min\", \"#{s} sec\"]\n units.reject{|str| str.start_with?(\"0\")}.join(\", \")\nend\n\n[7259, 86400, 6000000].each{|t| puts \"#{t}\\t: #{sec_to_str(t)}\"}"} {"title": "Count the coins", "language": "Ruby", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "def make_change(amount, coins)\n @cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)}\n @coins = coins\n do_count(amount, @coins.length - 1)\nend\n\ndef do_count(n, m)\n if n < 0 || m < 0\n 0\n elsif @cache[n][m]\n @cache[n][m]\n else\n @cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1)\n end\nend\n\np make_change( 1_00, [1,5,10,25])\np make_change(1000_00, [1,5,10,25,50,100])"} {"title": "Create an HTML table", "language": "Ruby", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "def r\n rand(10000)\nend\n\nSTDOUT << \"\".tap do |html|\n html << \"\"\n [\n ['X', 'Y', 'Z'],\n [r ,r ,r],\n [r ,r ,r],\n [r ,r ,r],\n [r ,r ,r]\n\n ].each_with_index do |row, index|\n html << \"\"\n html << \"\"\n html << row.map { |e| \"\"}.join\n html << \"\"\n end\n\n html << \"
#{index > 0 ? index : nil }#{e}
\"\nend\n"} {"title": "Cullen and Woodall numbers", "language": "Ruby", "task": "A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number.\n\nSo for each '''n''' the associated Cullen number and Woodall number differ by 2.\n\n''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''\n\n\n'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.\n\n\n;Task\n\n* Write procedures to find Cullen numbers and Woodall numbers. \n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\n\n;Stretch\n\n* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.\n\n* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.\n\n\n;See also\n\n* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1\n\n* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1\n\n* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime\n\n* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime\n\n\n", "solution": "require 'openssl'\n\ncullen = Enumerator.new{|y| (1..).each{|n| y << (n*(1< 6\np b.curry[1, 2][3, 4] #=> 6\np b.curry(5)[1][2][3][4][5] #=> 6\np b.curry(5)[1, 2][3, 4][5] #=> 6\np b.curry(1)[1] #=> 1\n\nb = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }\np b.curry[1][2][3] #=> 6\np b.curry[1, 2][3, 4] #=> 10\np b.curry(5)[1][2][3][4][5] #=> 15\np b.curry(5)[1, 2][3, 4][5] #=> 15\np b.curry(1)[1] #=> 1\n"} {"title": "Curzon numbers", "language": "Ruby", "task": "A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''.\n\n'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''.\n\n''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' \n\nGeneralized Curzon numbers only exist for even base integers. \n\n\n;Task \n\n* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.\n\n\n;Stretch\n\n* Find and show the '''one thousandth'''.\n\n\n;See also\n\n;* Numbers Aplenty - Curzon numbers\n;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)\n\n''and even though it is not specifically mentioned that they are Curzon numbers:''\n\n;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)\n\n", "solution": "def curzons(k)\n Enumerator.new do |y|\n (1..).each do |n|\n r = k * n\n y << n if k.pow(n, r + 1) == r\n end\n end\nend\n\n[2,4,6,8,10].each do |base|\n puts \"Curzon numbers with k = #{base}:\"\n puts curzons(base).take(50).join(\", \")\n puts \"Thousandth Curzon with k = #{base}: #{curzons(base).find.each.with_index(1){|_,i| i == 1000} }\",\"\"\nend"} {"title": "Cut a rectangle", "language": "Ruby from Python", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "def cut_it(h, w)\n if h.odd?\n return 0 if w.odd?\n h, w = w, h\n end\n return 1 if w == 1\n \n nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] # [next,dy,dx]\n blen = (h + 1) * (w + 1) - 1\n grid = [false] * (blen + 1)\n \n walk = lambda do |y, x, count=0|\n return count+1 if y==0 or y==h or x==0 or x==w\n t = y * (w + 1) + x\n grid[t] = grid[blen - t] = true\n nxt.each do |nt, dy, dx|\n count += walk[y + dy, x + dx] unless grid[t + nt]\n end\n grid[t] = grid[blen - t] = false\n count\n end\n \n t = h / 2 * (w + 1) + w / 2\n if w.odd?\n grid[t] = grid[t + 1] = true\n count = walk[h / 2, w / 2 - 1]\n count + walk[h / 2 - 1, w / 2] * 2\n else\n grid[t] = true\n count = walk[h / 2, w / 2 - 1]\n return count * 2 if h == w\n count + walk[h / 2 - 1, w / 2]\n end\nend\n\nfor w in 1..9\n for h in 1..w\n puts \"%d x %d: %d\" % [w, h, cut_it(w, h)] if (w * h).even?\n end\nend"} {"title": "Damm algorithm", "language": "Ruby", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "TABLE = [\n [0,3,1,7,5,9,8,6,4,2], [7,0,9,2,1,5,4,8,6,3],\n [4,2,0,6,8,7,1,3,5,9], [1,7,5,0,9,8,3,4,2,6],\n [6,1,2,3,0,4,5,9,7,8], [3,6,7,4,2,0,9,5,8,1],\n [5,8,6,9,7,2,0,1,3,4], [8,9,4,5,3,6,2,0,1,7],\n [9,4,3,8,6,1,7,2,0,5], [2,5,8,1,4,3,6,7,9,0]\n]\n\ndef damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| TABLE[idx][a] } == 0\n\n[5724, 5727, 112946].each{|n| puts \"#{n}: #{damm_valid?(n) ? \"\" : \"in\"}valid\"}\n"} {"title": "De Bruijn sequences", "language": "Ruby from D", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "def deBruijn(k, n)\n alphabet = \"0123456789\"\n @a = Array.new(k * n, 0)\n @seq = []\n\n def db(k, n, t, p)\n if t > n then\n if n % p == 0 then\n temp = @a[1 .. p]\n @seq.concat temp\n end\n else\n @a[t] = @a[t - p]\n db(k, n, t + 1, p)\n j = @a[t - p] + 1\n while j < k do\n @a[t] = j # & 0xFF\n db(k, n, t + 1, t)\n j = j + 1\n end\n end\n end\n db(k, n, 1, 1)\n\n buf = \"\"\n for i in @seq\n buf <<= alphabet[i]\n end\n return buf + buf[0 .. n-2]\nend\n\ndef validate(db)\n le = db.length\n found = Array.new(10000, 0)\n errs = []\n # Check all strings of 4 consecutive digits within 'db'\n # to see if all 10,000 combinations occur without duplication.\n for i in 0 .. le-4\n s = db[i .. i+3]\n if s.scan(/\\D/).empty? then\n found[s.to_i] += 1\n end\n end\n for i in 0 .. found.length - 1\n if found[i] == 0 then\n errs <<= (\" PIN number %04d missing\" % [i])\n elsif found[i] > 1 then\n errs <<= (\" PIN number %04d occurs %d times\" % [i, found[i]])\n end\n end\n if errs.length == 0 then\n print \" No errors found\\n\"\n else\n pl = (errs.length == 1) ? \"\" : \"s\"\n print \" \", errs.length, \" error\", pl, \" found:\\n\"\n for err in errs\n print err, \"\\n\"\n end\n end\nend\n\ndb = deBruijn(10, 4)\nprint \"The length of the de Bruijn sequence is \", db.length, \"\\n\\n\"\nprint \"The first 130 digits of the de Bruijn sequence are: \", db[0 .. 129], \"\\n\\n\"\nprint \"The last 130 digits of the de Bruijn sequence are: \", db[-130 .. db.length], \"\\n\\n\"\n\nprint \"Validating the de Bruijn sequence:\\n\"\nvalidate(db)\nprint \"\\n\"\n\ndb[4443] = '.'\nprint \"Validating the overlaid de Bruijn sequence:\\n\"\nvalidate(db)"} {"title": "Deceptive numbers", "language": "Ruby", "task": "Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation '''Rn''' symbolizes the repunit made up of '''n''' ones.\n\nEvery prime '''p''' larger than 5, evenly divides the repunit '''Rp-1'''.\n\n\n;E.G.\n\nThe repunit '''R6''' is evenly divisible by '''7'''.\n\n111111 / 7 = 15873\n\nThe repunit '''R42''' is evenly divisible by '''43'''.\n\n111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677\n\nAnd so on.\n\n\nThere are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''.\n\n\nThe repunit '''R90''' is evenly divisible by the composite number '''91''' (=7*13).\n\n111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221\n\n\n;Task \n\n* Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''Rn-1'''\n\n\n;See also\n\n;* Numbers Aplenty - Deceptive numbers\n;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}\n\n", "solution": "require 'prime'\n\ndeceptives = Enumerator.new do |y|\n 10.step(by: 10) do |n|\n [1,3,7,9].each do |digit|\n cand = n + digit\n next if cand % 3 == 0 || cand.prime? \n repunit = (\"1\"*(cand-1)).to_i\n y << cand if (repunit % cand) == 0\n end\n end\nend\n\np deceptives.take(25).to_a\n"} {"title": "Deepcopy", "language": "Ruby", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "# _orig_ is a Hash that contains an Array.\norig = { :num => 1, :ary => [2, 3] }\norig[:cycle] = orig\t# _orig_ also contains itself.\n\n# _copy_ becomes a deep copy of _orig_.\ncopy = Marshal.load(Marshal.dump orig)\n\n# These changes to _orig_ never affect _copy_,\n# because _orig_ and _copy_ are disjoint structures.\norig[:ary] << 4\norig[:rng] = (5..6)\n\n# Because of deep copy, orig[:ary] and copy[:ary]\n# refer to different Arrays.\np orig\t# => {:num=>1, :ary=>[2, 3, 4], :cycle=>{...}, :rng=>5..6}\np copy\t# => {:num=>1, :ary=>[2, 3], :cycle=>{...}}\n\n# The original contains itself, and the copy contains itself,\n# but the original and the copy are not the same object.\np [(orig.equal? orig[:cycle]),\n (copy.equal? copy[:cycle]),\n (not orig.equal? copy)]\t# => [true, true, true]"} {"title": "Deming's funnel", "language": "Ruby from Python", "task": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* '''Rule 1''': The funnel remains directly above the target.\n* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* '''Rule 4''': The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. \n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n'''Stretch goal 2''': Show scatter plots of all four results.\n\n\n;Further information:\n* Further explanation and interpretation\n* Video demonstration of the funnel experiment at the Mayo Clinic.\n\n", "solution": "def funnel(dxs, &rule)\n x, rxs = 0, []\n for dx in dxs\n rxs << (x + dx)\n x = rule[x, dx]\n end\n rxs\nend\n\ndef mean(xs) xs.inject(:+) / xs.size end\n\ndef stddev(xs)\n m = mean(xs)\n Math.sqrt(xs.inject(0.0){|sum,x| sum + (x-m)**2} / xs.size)\nend\n\ndef experiment(label, dxs, dys, &rule)\n rxs, rys = funnel(dxs, &rule), funnel(dys, &rule)\n puts label\n puts 'Mean x, y : %7.4f, %7.4f' % [mean(rxs), mean(rys)]\n puts 'Std dev x, y : %7.4f, %7.4f' % [stddev(rxs), stddev(rys)]\n puts\nend\n\ndxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n 0.443, -0.521, -0.799, 0.087]\n\ndys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n -0.947, -1.424, -0.542, -1.032]\n\nexperiment('Rule 1:', dxs, dys) {|z, dz| 0}\nexperiment('Rule 2:', dxs, dys) {|z, dz| -dz}\nexperiment('Rule 3:', dxs, dys) {|z, dz| -(z+dz)}\nexperiment('Rule 4:', dxs, dys) {|z, dz| z+dz}"} {"title": "Department numbers", "language": "Ruby", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }\n"} {"title": "Descending primes", "language": "Ruby", "task": "Generate and show all primes with strictly descending decimal digits.\n\n;See also\n;* OEIS:A052014 - Primes with distinct digits in descending order\n\n;Related:\n*[[Ascending primes]]\n\n\n", "solution": "require 'prime'\n\ndigits = [9,8,7,6,5,4,3,2,1].to_a\nres = 1.upto(digits.size).flat_map do |n|\n digits.combination(n).filter_map do |set|\n candidate = set.join.to_i\n candidate if candidate.prime?\n end.reverse\n end\n\n puts res.join(\",\")"} {"title": "Detect division by zero", "language": "Ruby", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "def div_check(x, y)\n begin\n x / y\n rescue ZeroDivisionError\n true\n else\n false\n end\nend"} {"title": "Detect division by zero", "language": "Ruby 1.9", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "def div_check(x, y)\n begin\n x.div y\n rescue ZeroDivisionError\n true\n else\n false\n end\nend"} {"title": "Determinant and permanent", "language": "Ruby", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "require 'matrix'\n\nclass Matrix\n # Add \"permanent\" method to Matrix class\n def permanent\n r = (0...row_count).to_a # [0,1] (first example), [0,1,2,3] (second example)\n r.permutation.inject(0) do |sum, sigma|\n sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] }\n end\n end\nend\n\nm1 = Matrix[[1,2],[3,4]] # testcases from Python version\n\nm2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]]\n\nm3 = Matrix[[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19], \n [20, 21, 22, 23, 24]]\n\n[m1, m2, m3].each do |m|\n puts \"determinant:\\t #{m.determinant}\", \"permanent:\\t #{m.permanent}\"\n puts \nend"} {"title": "Determine if a string has all the same characters", "language": "Ruby", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "strings = [\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\", \"p\u00e9p\u00e9\", \"\ud83d\udc36\ud83d\udc36\ud83d\udc3a\ud83d\udc36\", \"\ud83c\udf84\ud83c\udf84\ud83c\udf84\ud83c\udf84\"]\n\nstrings.each do |str|\n pos = str.empty? ? nil : str =~ /[^#{str[0]}]/\n print \"#{str.inspect} (size #{str.size}): \"\n puts pos ? \"first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}.\" : \"all the same.\"\nend\n"} {"title": "Determine if a string has all unique characters", "language": "Ruby", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "strings = [\"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"h\u00e9t\u00e9rog\u00e9n\u00e9it\u00e9\",\n \"\ud83c\udf86\ud83c\udf83\ud83c\udf87\ud83c\udf88\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude4c\",\n \"\ud83d\udc20\ud83d\udc1f\ud83d\udc21\ud83e\udd88\ud83d\udc2c\ud83d\udc33\ud83d\udc0b\ud83d\udc21\",]\n\nstrings.each do |str|\n seen = {}\n print \"#{str.inspect} (size #{str.size}) \"\n res = \"has no duplicates.\" #may change\n str.chars.each_with_index do |c,i|\n if seen[c].nil? \n seen[c] = i\n else\n res = \"has duplicate char #{c} (#{'%#x' % c.ord}) on #{seen[c]} and #{i}.\"\n break\n end\n end\n puts res\nend\n"} {"title": "Determine if a string is collapsible", "language": "Ruby", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "strings = [\"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",]\n\nstrings.each do |str|\n puts \"\u00ab\u00ab\u00ab#{str}\u00bb\u00bb\u00bb (size #{str.size})\"\n ssq = str.squeeze\n puts \"\u00ab\u00ab\u00ab#{ssq}\u00bb\u00bb\u00bb (size #{ssq.size})\"\n puts\nend\n"} {"title": "Determine if a string is squeezable", "language": "Ruby", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "strings = [\"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",]\nsqueeze_these = [\"\", \"-\", \"7\", \".\", \" -r\", \"\ud83d\ude0d\"]\n\nstrings.zip(squeeze_these).each do |str, st|\n puts \"original: \u00ab\u00ab\u00ab#{str}\u00bb\u00bb\u00bb (size #{str.size})\"\n st.chars.each do |c|\n ssq = str.squeeze(c)\n puts \"#{c.inspect}-squeezed: \u00ab\u00ab\u00ab#{ssq}\u00bb\u00bb\u00bb (size #{ssq.size})\" \n end\n puts\nend\n"} {"title": "Determine if two triangles overlap", "language": "Ruby from C", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\n", "solution": "require \"matrix\"\n\ndef det2D(p1, p2, p3)\n return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])\nend\n\ndef checkTriWinding(p1, p2, p3, allowReversed)\n detTri = det2D(p1, p2, p3)\n if detTri < 0.0 then\n if allowReversed then\n p2[0], p3[0] = p3[0], p2[0]\n p2[1], p3[1] = p3[1], p2[1]\n else\n raise \"Triangle has incorrect winding\"\n end\n end\nend\n\ndef boundaryCollideChk(p1, p2, p3, eps)\n return det2D(p1, p2, p3) < eps\nend\n\ndef boundaryDoesntCollideChk(p1, p2, p3, eps)\n return det2D(p1, p2, p3) <= eps\nend\n\ndef triTri2D(t1, t2, eps, allowReversed, onBoundary)\n # Triangles must be expressed anti-clockwise\n checkTriWinding(t1[0], t1[1], t1[2], allowReversed)\n checkTriWinding(t2[0], t2[1], t2[2], allowReversed)\n\n if onBoundary then\n # Points on the boundary are considered as colliding\n chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) }\n else\n # Points on the boundary are not considered as colliding\n chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) }\n end\n\n # For edge E of triangle 1\n for i in 0..2 do\n j = (i + 1) % 3\n\n # Check all points of trangle 2 lay on the external side of the edge E. If\n # they do, the triangles do not collide.\n if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then\n return false\n end\n end\n\n # For edge E of triangle 2\n for i in 0..2 do\n j = (i + 1) % 3\n\n # Check all points of trangle 1 lay on the external side of the edge E. If\n # they do, the triangles do not collide.\n if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then\n return false\n end\n end\n\n # The triangles collide\n return true\nend\n\ndef main\n t1 = [Vector[0,0], Vector[5,0], Vector[0,5]]\n t2 = [Vector[0,0], Vector[5,0], Vector[0,6]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[0,5], Vector[5,0]]\n t2 = [Vector[0,0], Vector[0,5], Vector[5,0]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, true, true)]\n\n t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]]\n t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]]\n t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[1,1], Vector[0,2]]\n t2 = [Vector[2,1], Vector[3,0], Vector[3,2]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]]\n t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n # Barely touching\n t1 = [Vector[0,0], Vector[1,0], Vector[0,1]]\n t2 = [Vector[1,0], Vector[2,0], Vector[1,1]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, true)]\n\n # Barely touching\n t1 = [Vector[0,0], Vector[1,0], Vector[0,1]]\n t2 = [Vector[1,0], Vector[2,0], Vector[1,1]]\n print \"Triangle: \", t1, \"\\n\"\n print \"Triangle: \", t2, \"\\n\"\n print \"overlap: %s\\n\\n\" % [triTri2D(t1, t2, 0.0, false, false)]\nend\n\nmain()"} {"title": "Dice game probabilities", "language": "Ruby", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "def roll_dice(n_dice, n_faces)\n return [[0,1]] if n_dice.zero?\n one = [1] * n_faces\n zero = [0] * (n_faces-1)\n (1...n_dice).inject(one){|ary,_|\n (zero + ary + zero).each_cons(n_faces).map{|a| a.inject(:+)}\n }.map.with_index(n_dice){|n,sum| [sum,n]} # sum: total of the faces\nend\n\ndef game(dice1, faces1, dice2, faces2)\n p1 = roll_dice(dice1, faces1)\n p2 = roll_dice(dice2, faces2)\n p1.product(p2).each_with_object([0,0,0]) do |((sum1, n1), (sum2, n2)), win|\n win[sum1 <=> sum2] += n1 * n2 # [0]:draw, [1]:win, [-1]:lose\n end\nend\n\n[[9, 4, 6, 6], [5, 10, 6, 7]].each do |d1, f1, d2, f2|\n puts \"player 1 has #{d1} dice with #{f1} faces each\"\n puts \"player 2 has #{d2} dice with #{f2} faces each\"\n win = game(d1, f1, d2, f2)\n sum = win.inject(:+)\n puts \"Probability for player 1 to win: #{win[1]} / #{sum}\",\n \" -> #{win[1].fdiv(sum)}\", \"\"\nend"} {"title": "Digital root", "language": "Ruby", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "class String\n def digroot_persistence(base=10)\n num = self.to_i(base)\n persistence = 0\n until num < base do\n num = num.digits(base).sum\n persistence += 1\n end\n [num.to_s(base), persistence]\n end\nend\n\nputs \"--- Examples in 10-Base ---\"\n%w(627615 39390 588225 393900588225).each do |str|\n puts \"%12s has a digital root of %s and a persistence of %s.\" % [str, *str.digroot_persistence]\nend\nputs \"\\n--- Examples in other Base ---\"\nformat = \"%s base %s has a digital root of %s and a persistence of %s.\"\n[[\"101101110110110010011011111110011000001\", 2],\n [ \"5BB64DFCC1\", 16],\n [\"5\", 8],\n [\"50YE8N29\", 36]].each do |(str, base)|\n puts format % [str, base, *str.digroot_persistence(base)]\nend"} {"title": "Disarium numbers", "language": "Ruby", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "disariums = Enumerator.new do |y|\n (0..).each do |n|\n i = 0\n y << n if n.digits.reverse.sum{|d| d ** (i+=1) } == n\n end\nend\n\nputs disariums.take(19).to_a.join(\" \")\n"} {"title": "Display a linear combination", "language": "Ruby from D", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "def linearCombo(c)\n sb = \"\"\n c.each_with_index { |n, i|\n if n == 0 then\n next\n end\n if n < 0 then\n if sb.length == 0 then\n op = \"-\"\n else\n op = \" - \"\n end\n elsif n > 0 then\n if sb.length > 0 then\n op = \" + \"\n else\n op = \"\"\n end\n else\n op = \"\"\n end\n av = n.abs()\n if av != 1 then\n coeff = \"%d*\" % [av]\n else\n coeff = \"\"\n end\n sb = sb + \"%s%se(%d)\" % [op, coeff, i + 1]\n }\n if sb.length == 0 then\n return \"0\"\n end\n return sb\nend\n\ndef main\n combos = [\n [1, 2, 3],\n [0, 1, 2, 3],\n [1, 0, 3, 4],\n [1, 2, 0],\n [0, 0, 0],\n [0],\n [1, 1, 1],\n [-1, -1, -1],\n [-1, -2, 0, -3],\n [-1],\n ]\n\n for c in combos do\n print \"%-15s -> %s\\n\" % [c, linearCombo(c)]\n end\nend\n\nmain()"} {"title": "Distance and Bearing", "language": "Ruby", "task": "It is very important in aviation to have knowledge of the nearby airports at any time in flight. \n;Task:\nDetermine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested.\nUse the non-commercial data from openflights.org airports.dat as reference.\n\n\nA request comes from an airplane at position ( latitude, longitude ): ( '''51.514669, 2.198581''' ).\n\n\nYour report should contain the following information from table airports.dat (column shown in brackets):\n\nName(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8). \n\n\nDistance is measured in nautical miles (NM). Resolution is 0.1 NM.\n\nBearing is measured in degrees (deg). 0deg = 360deg = north then clockwise 90deg = east, 180deg = south, 270deg = west. Resolution is 1deg.\n \n\n;See:\n:* openflights.org/data: Airport, airline and route data\n:* Movable Type Scripts: Calculate distance, bearing and more between Latitude/Longitude points\n\n", "solution": "require 'open-uri'\nrequire 'csv'\ninclude Math\n\nRADIUS = 6372.8 # rough radius of the Earth, in kilometers\n\ndef spherical_distance(start_coords, end_coords)\n lat1, long1 = deg2rad(*start_coords)\n lat2, long2 = deg2rad(*end_coords)\n 2 * RADIUS * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2))\nend\n\ndef bearing(start_coords, end_coords)\n lat1, long1 = deg2rad(*start_coords)\n lat2, long2 = deg2rad(*end_coords)\n dlon = long2 - long1\n atan2(sin(dlon) * cos(lat2), cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon))\nend\n\ndef deg2rad(lat, long)\n [lat * PI / 180, long * PI / 180]\nend\n\nuri = \"https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat\"\nheaders = %i(airportID\n name\n city\n country\n iata\n icao\n latitude\n longitude\n altitude\n timezone\n dst\n tzOlson\n type\n source)\ndata = CSV.parse(URI.open(uri), headers: headers, converters: :numeric)\n\nposition = [51.514669, 2.198581]\n\ndata.each{|r| r[:dist] = (spherical_distance(position, [r[:latitude], r[:longitude]])/1.852).round(1)}\nclosest = data.min_by(20){|row| row[:dist] }\nclosest.each do |r|\n bearing = (bearing(position,[r[:latitude], r[:longitude]])*180/PI).round % 360\n puts \"%-40s %-25s %-6s %12.1f %15.0f\" % (r.values_at(:name, :country, :ICAO, :dist) << bearing)\nend\n"} {"title": "Diversity prediction theorem", "language": "Ruby from D", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "def mean(a) = a.sum(0.0) / a.size\ndef mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 })\n \ndef diversity_theorem(truth, predictions)\n average = mean(predictions)\n puts \"truth: #{truth}, predictions #{predictions}\",\n \"average-error: #{mean_square_diff(truth, predictions)}\",\n \"crowd-error: #{(truth - average)**2}\",\n \"diversity: #{mean_square_diff(average, predictions)}\",\"\"\nend\n \ndiversity_theorem(49.0, [48.0, 47.0, 51.0])\ndiversity_theorem(49.0, [48.0, 47.0, 51.0, 42.0])"} {"title": "Dot product", "language": "Ruby", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "class Array\n def dot_product(other)\n raise \"not the same size!\" if self.length != other.length\n zip(other).sum {|a, b| a*b}\n end\nend\n\np [1, 3, -5].dot_product [4, -2, -1] # => 3"} {"title": "Dutch national flag problem", "language": "Ruby", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "class Ball\n FLAG = {red: 1, white: 2, blue: 3}\n \n def initialize\n @color = FLAG.keys.sample\n end\n\n def color\n @color\n end\n\n def <=>(other) # needed for sort, results in -1 for <, 0 for == and 1 for >.\n FLAG[self.color] <=> FLAG[other.color]\n end\n\n def inspect\n @color\n end\nend\n\nballs = [] \nballs = Array.new(8){Ball.new} while balls == balls.sort\n\nputs \"Random: #{balls}\"\nputs \"Sorted: #{balls.sort}\"\n "} {"title": "Eban numbers", "language": "Ruby from C#", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count\n:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count\n:::* show a count of all eban numbers up and including '''10,000'''\n:::* show a count of all eban numbers up and including '''100,000'''\n:::* show a count of all eban numbers up and including '''1,000,000'''\n:::* show a count of all eban numbers up and including '''10,000,000'''\n:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "def main\n intervals = [\n [2, 1000, true],\n [1000, 4000, true],\n [2, 10000, false],\n [2, 100000, false],\n [2, 1000000, false],\n [2, 10000000, false],\n [2, 100000000, false],\n [2, 1000000000, false]\n ]\n for intv in intervals\n (start, ending, display) = intv\n if start == 2 then\n print \"eban numbers up to and including %d:\\n\" % [ending]\n else\n print \"eban numbers between %d and %d (inclusive):\\n\" % [start, ending]\n end\n\n count = 0\n for i in (start .. ending).step(2)\n b = (i / 1000000000).floor\n r = (i % 1000000000)\n m = (r / 1000000).floor\n r = (r % 1000000)\n t = (r / 1000).floor\n r = (r % 1000)\n if m >= 30 and m <= 66 then\n m = m % 10\n end\n if t >= 30 and t <= 66 then\n t = t % 10\n end\n if r >= 30 and r <= 66 then\n r = r % 10\n end\n if b == 0 or b == 2 or b == 4 or b == 6 then\n if m == 0 or m == 2 or m == 4 or m == 6 then\n if t == 0 or t == 2 or t == 4 or t == 6 then\n if r == 0 or r == 2 or r == 4 or r == 6 then\n if display then\n print ' ', i\n end\n count = count + 1\n end\n end\n end\n end\n end\n if display then\n print \"\\n\"\n end\n print \"count = %d\\n\\n\" % [count]\n end\nend\n\nmain()"} {"title": "Eertree", "language": "Ruby from D", "task": "An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. \n\nThe data structure has commonalities to both ''tries'' and ''suffix trees''.\n See links below. \n\n\n;Task:\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\n\n;See also:\n* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n\n", "solution": "class Node\n def initialize(length, edges = {}, suffix = 0)\n @length = length\n @edges = edges\n @suffix = suffix\n end\n\n attr_reader :length\n attr_reader :edges\n attr_accessor :suffix\nend\n\nEVEN_ROOT = 0\nODD_ROOT = 1\n\ndef eertree(s)\n tree = [\n Node.new(0, {}, ODD_ROOT),\n Node.new(-1, {}, ODD_ROOT)\n ]\n suffix = ODD_ROOT\n s.each_char.with_index { |c, i|\n n = suffix\n k = 0\n loop do\n k = tree[n].length\n b = i - k - 1\n if b >= 0 and s[b] == c then\n break\n end\n n = tree[n].suffix\n end\n if tree[n].edges.key?(c) then\n suffix = tree[n].edges[c]\n next\n end\n suffix = tree.length\n tree << Node.new(k + 2)\n tree[n].edges[c] = suffix\n if tree[suffix].length == 1 then\n tree[suffix].suffix = 0\n next\n end\n loop do\n n = tree[n].suffix\n b = i - tree[n].length - 1\n if b >= 0 and s[b] == c then\n break\n end\n end\n tree[suffix].suffix = tree[n].edges[c]\n }\n return tree\nend\n\ndef subPalindromes(tree)\n s = []\n\n children = lambda { |n,p,f|\n for c,v in tree[n].edges\n m = tree[n].edges[c]\n p = c + p + c\n s << p\n f.call(m, p, f)\n end\n }\n\n children.call(0, '', children)\n\n for c,n in tree[1].edges\n s << c\n children.call(n, c, children)\n end\n\n return s\nend\n\ntree = eertree(\"eertree\")\nprint subPalindromes(tree), \"\\n\""} {"title": "Egyptian division", "language": "Ruby", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "def egyptian_divmod(dividend, divisor)\n table = [[1, divisor]]\n table << table.last.map{|e| e*2} while table.last.first * 2 <= dividend\n answer, accumulator = 0, 0\n table.reverse_each do |pow, double|\n if accumulator + double <= dividend\n accumulator += double\n answer += pow\n end\n end\n [answer, dividend - accumulator] \nend\n\nputs \"Quotient = %s Remainder = %s\" % egyptian_divmod(580, 34)\n"} {"title": "Elementary cellular automaton", "language": "Ruby", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "class ElemCellAutomat\n include Enumerable\n \n def initialize (start_str, rule, disp=false)\n @cur = start_str\n @patterns = Hash[8.times.map{|i|[\"%03b\"%i, \"01\"[rule[i]]]}]\n puts \"Rule (#{rule}) : #@patterns\" if disp\n end\n \n def each\n return to_enum unless block_given?\n loop do\n yield @cur\n str = @cur[-1] + @cur + @cur[0]\n @cur = @cur.size.times.map {|i| @patterns[str[i,3]]}.join\n end\n end\n \nend\n\neca = ElemCellAutomat.new('1'.center(39, \"0\"), 18, true)\neca.take(30).each{|line| puts line.tr(\"01\", \".#\")}"} {"title": "Elementary cellular automaton/Infinite length", "language": "Ruby from Python", "task": "The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.\n\nTo be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.\n\nExamples:\n\n\n1 -> ..., 0, 0, 1, 0, 0, ...\n0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...\n1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...\n\n\nMore complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.\n\n", "solution": "def notcell(c)\n c.tr('01','10')\nend\n\ndef eca_infinite(cells, rule)\n neighbours2next = Hash[8.times.map{|i|[\"%03b\"%i, \"01\"[rule[i]]]}]\n c = cells\n Enumerator.new do |y|\n loop do\n y << c\n c = notcell(c[0])*2 + c + notcell(c[-1])*2 # Extend and pad the ends\n c = (1..c.size-2).map{|i| neighbours2next[c[i-1..i+1]]}.join\n end\n end\nend\n\nif __FILE__ == $0\n lines = 25\n for rule in [90, 30]\n puts \"\\nRule: %i\" % rule\n for i, c in (0...lines).zip(eca_infinite('1', rule))\n puts '%2i: %s%s' % [i, ' '*(lines - i), c.tr('01', '.#')]\n end\n end\nend"} {"title": "Elementary cellular automaton/Random number generator", "language": "Ruby", "task": "Mathematica software for its default random number generator.\n\nSteven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.\n\nThe purpose of this task is to demonstrate this. With the code written in the most significant.\n\nYou can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.\n\nFor extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.\n\n;Reference:\n* Cellular automata: Is Rule 30 random? (PDF).\n\n\n", "solution": "size = 100\neca = ElemCellAutomat.new(\"1\"+\"0\"*(size-1), 30)\neca.take(80).map{|line| line[0]}.each_slice(8){|bin| p bin.join.to_i(2)}"} {"title": "Empty string", "language": "Ruby", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "s == \"\"\ns.eql?(\"\")\ns.empty?\ns.length == 0\ns[/\\A\\z/]\n\n# also silly things like\ns.each_char.to_a.empty?"} {"title": "Entropy/Narcissist", "language": "Ruby", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "def entropy(s)\n counts = s.each_char.tally\n size = s.size.to_f\n counts.values.reduce(0) do |entropy, count|\n freq = count / size\n entropy - freq * Math.log2(freq)\n end\nend\n\ns = File.read(__FILE__)\np entropy(s)\n"} {"title": "Equilibrium index", "language": "Ruby", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "def eq_indices(list)\n result = []\n list.empty? and return result\n final = list.size - 1\n \n helper = lambda do |left, current, right, index|\n left == right and result << index # Push index to result?\n index == final and return # Terminate recursion?\n new = list[index + 1]\n helper.call(left + current, new, right - new, index + 1)\n end\n helper.call 0, list.first, list.drop(1).sum, 0\n result\nend"} {"title": "Esthetic numbers", "language": "Ruby from Kotlin", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "def isEsthetic(n, b)\n if n == 0 then\n return false\n end\n\n i = n % b\n n2 = (n / b).floor\n while n2 > 0\n j = n2 % b\n if (i - j).abs != 1 then\n return false\n end\n n2 = n2 / b\n i = j\n end\n return true\nend\n\ndef listEsths(n, n2, m, m2, perLine, all)\n esths = Array.new\n dfs = lambda {|n, m, i|\n if n <= i and i <= m then\n esths << i\n end\n if i == 0 or i > m then\n return\n end\n d = i % 10\n i1 = i * 10 + d - 1\n i2 = i1 + 2\n if d == 0 then\n dfs[n, m, i2]\n elsif d == 9 then\n dfs[n, m, i1]\n else\n dfs[n, m, i1]\n dfs[n, m, i2]\n end\n }\n\n for i in 0..9\n dfs[n2, m2, i]\n end\n\n le = esths.length\n print \"Base 10: %d esthetic numbers between %d and %d:\\n\" % [le, n, m]\n if all then\n esths.each_with_index { |esth, idx|\n print \"%d \" % [esth]\n if (idx + 1) % perLine == 0 then\n print \"\\n\"\n end\n }\n print \"\\n\"\n else\n for i in 0 .. perLine - 1\n print \"%d \" % [esths[i]]\n end\n print \"\\n............\\n\"\n for i in le - perLine .. le - 1\n print \"%d \" % [esths[i]]\n end\n print \"\\n\"\n end\n print \"\\n\"\nend\n\ndef main\n for b in 2..16\n print \"Base %d: %dth to %dth esthetic numbers:\\n\" % [b, 4 * b, 6 * b]\n n = 1\n c = 0\n while c < 6 * b\n if isEsthetic(n, b) then\n c = c + 1\n if c >= 4 * b then\n print \"%s \" % [n.to_s(b)]\n end\n end\n n = n + 1\n end\n print \"\\n\"\n end\n print \"\\n\"\n\n listEsths(1000, 1010, 9999, 9898, 16, true)\n listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true)\n listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false)\n listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false)\n listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false)\nend\n\nmain()"} {"title": "Euler's sum of powers conjecture", "language": "Ruby", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "power5 = (1..250).each_with_object({}){|i,h| h[i**5]=i}\nresult = power5.keys.repeated_combination(4).select{|a| power5[a.inject(:+)]}\nputs result.map{|a| a.map{|i| \"#{power5[i]}**5\"}.join(' + ') + \" = #{power5[a.inject(:+)]}**5\"}"} {"title": "Euler's sum of powers conjecture", "language": "Ruby from Python", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "p5, sum2, max = {}, {}, 250\n(1..max).each do |i|\n p5[i**5] = i\n (i..max).each{|j| sum2[i**5 + j**5] = [i,j]}\nend\n\nresult = {}\nsk = sum2.keys.sort\np5.keys.sort.each do |p|\n sk.each do |s|\n break if p <= s\n result[(sum2[s] + sum2[p-s]).sort] = p5[p] if sum2[p - s]\n end\nend\nresult.each{|k,v| puts k.map{|i| \"#{i}**5\"}.join(' + ') + \" = #{v}**5\"}"} {"title": "Even or odd", "language": "Ruby", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "print \"evens: \"\np -5.upto(5).select(&:even?)\nprint \"odds: \"\np -5.upto(5).select(&:odd?)"} {"title": "Evolutionary algorithm", "language": "Ruby from C", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "@target = \"METHINKS IT IS LIKE A WEASEL\"\nCharset = [\" \", *\"A\"..\"Z\"]\nCOPIES = 100\n\ndef random_char; Charset.sample end\n\ndef fitness(candidate)\n sum = 0\n candidate.chars.zip(@target.chars) {|x,y| sum += (x[0].ord - y[0].ord).abs}\n 100.0 * Math.exp(Float(sum) / -10.0)\nend\n\ndef mutation_rate(candidate)\n 1.0 - Math.exp( -(100.0 - fitness(candidate)) / 400.0)\nend\n\ndef mutate(parent, rate)\n parent.each_char.collect {|ch| rand <= rate ? random_char : ch}.join\nend\n\ndef log(iteration, rate, parent)\n puts \"%4d %.2f %5.1f %s\" % [iteration, rate, fitness(parent), parent]\nend\n\niteration = 0\nparent = Array.new(@target.length) {random_char}.join\nprev = \"\"\n\nwhile parent != @target\n iteration += 1\n rate = mutation_rate(parent)\n if prev != parent\n log(iteration, rate, parent)\n prev = parent\n end\n copies = [parent] + Array.new(COPIES) {mutate(parent, rate)}\n parent = copies.max_by {|c| fitness(c)}\nend\nlog(iteration, rate, parent)"} {"title": "Executable library", "language": "Ruby", "task": "The general idea behind an executable library is to create a library \nthat when used as a library does one thing; \nbut has the ability to be run directly via command line. \nThus the API comes with a CLI in the very same source code file.\n\n'''Task detail'''\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:\n:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n'''Notes:''' \n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.\n* Interpreters are present in the runtime environment.\n\n", "solution": "An executable library checks ''__FILE__ == $0''. Here, ''__FILE__'' is the path \nof the current source file, and ''$0'' is the path of the current executable. \nIf ''__FILE__ == $0'', then the current source file is the executable, \nelse the current source file is a library for some other executable.\n\n* ''__FILE__ == $0'' also works with older versions of Ruby, but this Hailstone example calls new methods in Ruby 1.8.7.\n\nThis is ''hailstone.rb'', a modification of [[Hailstone sequence#Ruby]] as an executable library.\n\n"} {"title": "Executable library", "language": "Ruby 1.8.7", "task": "The general idea behind an executable library is to create a library \nthat when used as a library does one thing; \nbut has the ability to be run directly via command line. \nThus the API comes with a CLI in the very same source code file.\n\n'''Task detail'''\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:\n:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n'''Notes:''' \n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.\n* Interpreters are present in the runtime environment.\n\n", "solution": "# hailstone.rb\nmodule Hailstone\n module_function\n def hailstone n\n seq = [n]\n until n == 1\n n = (n.even?) ? (n / 2) : (3 * n + 1)\n seq << n\n end\n seq\n end\nend\n\nif __FILE__ == $0\n include Hailstone\n\n # for n = 27, show sequence length and first and last 4 elements\n hs27 = hailstone 27\n p [hs27.length, hs27[0..3], hs27[-4..-1]]\n\n # find the longest sequence among n less than 100,000\n n, len = (1 ... 100_000) .collect {|n|\n [n, hailstone(n).length]} .max_by {|n, len| len}\n puts \"#{n} has a hailstone sequence length of #{len}\"\n puts \"the largest number in that sequence is #{hailstone(n).max}\"\nend"} {"title": "Exponentiation order", "language": "Ruby", "task": "This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.\n\n(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)\n\n\n;Task requirements\nShow the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nUsing whatever operator or syntax your language supports (if any), show the results in three lines (with identification):\n \n::::* 5**3**2 \n::::* (5**3)**2\n::::* 5**(3**2)\n\n\nIf there are other methods (or formats) of multiple exponentiations, show them as well. \n\n\n;See also:\n* MathWorld entry: exponentiation\n\n\n;Related tasks:\n* exponentiation operator\n* arbitrary-precision integers (included)\n* [[Exponentiation with infix operators in (or operating on) the base]]\n\n", "solution": "ar = [\"5**3**2\", \"(5**3)**2\", \"5**(3**2)\", \"[5,3,2].inject(:**)\"]\nar.each{|exp| puts \"#{exp}:\\t#{eval exp}\"}\n"} {"title": "Exponentiation with infix operators in (or operating on) the base", "language": "Ruby", "task": "(Many programming languages, especially those with extended-precision integer arithmetic, usually\nsupport one of **, ^, | or some such for exponentiation.)\n\n\nSome languages treat/honor infix operators when performing exponentiation (raising\nnumbers to some power by the language's exponentiation operator, if the computer\nprogramming language has one).\n\n\nOther programming languages may make use of the '''POW''' or some other BIF\n ('''B'''uilt-'''I'''n '''F'''function), or some other library service.\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nThis task will deal with the case where there is some form of an ''infix operator'' operating\nin (or operating on) the base.\n\n\n;Example:\nA negative five raised to the 3rd power could be specified as:\n -5 ** 3 or as\n -(5) ** 3 or as\n (-5) ** 3 or as something else\n\n\n(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).\n\n\n;Task:\n:* compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.\n:* Raise the following numbers (integer or real):\n:::* -5 and\n:::* +5\n:* to the following powers:\n:::* 2nd and\n:::* 3rd\n:* using the following expressions (if applicable in your language):\n:::* -x**p\n:::* -(x)**p\n:::* (-x)**p\n:::* -(x**p)\n:* Show here (on this page) the four (or more) types of symbolic expressions for each number and power.\n\n\nTry to present the results in the same format/manner as the other programming entries to make any differences apparent.\n\n\nThe variables may be of any type(s) that is/are applicable in your language.\n\n\n;Related tasks:\n* [[Exponentiation order]]\n* [[Exponentiation operator]]\n* [[Arbitrary-precision integers (included)]]\n* [[Parsing/RPN to infix conversion]]\n* [[Operator precedence]]\n\n;References:\n* Wikipedia: Order of operations in Programming languages\n\n", "solution": "nums = [-5, 5]\npows = [2, 3]\nnums.product(pows) do |x, p|\n puts \"x = #{x} p = #{p}\\t-x**p #{-x**p}\\t-(x)**p #{-(x)**p}\\t(-x)**p #{ (-x)**p}\\t-(x**p) #{-(x**p)}\"\nend\n"} {"title": "Extend your language", "language": "Ruby", "task": "{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.\n\nIf your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:\n\nOccasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are \"true\"). In a C-like language this could look like the following:\n\n if (condition1isTrue) {\n if (condition2isTrue)\n bothConditionsAreTrue();\n else\n firstConditionIsTrue();\n }\n else if (condition2isTrue)\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nBesides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.\n\nThis can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:\n\n if2 (condition1isTrue) (condition2isTrue)\n bothConditionsAreTrue();\n else1\n firstConditionIsTrue();\n else2\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nPick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.\n", "solution": "# Define a class which always returns itself for everything\nclass HopelesslyEgocentric\n def method_missing(what, *args) self end\nend\n\ndef if2(cond1, cond2)\n if cond1 and cond2\n yield\n HopelesslyEgocentric.new\n elsif cond1\n Class.new(HopelesslyEgocentric) do\n def else1; yield; HopelesslyEgocentric.new end\n end.new\n elsif cond2\n Class.new(HopelesslyEgocentric) do\n def else2; yield; HopelesslyEgocentric.new end\n end.new\n else\n Class.new(HopelesslyEgocentric) do\n def neither; yield end\n end.new\n end\nend"} {"title": "Extreme floating point values", "language": "Ruby", "task": "The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.\n\nThe task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. \n\nPrint the values of these variables if possible; and show some arithmetic with these values and variables. \n\nIf your language can directly enter these extreme floating point values then show it.\n\n\n;See also:\n* What Every Computer Scientist Should Know About Floating-Point Arithmetic\n\n\n;Related tasks:\n* [[Infinity]]\n* [[Detect division by zero]]\n* [[Literals/Floating point]]\n\n", "solution": "inf = 1.0 / 0.0 # or Float::INFINITY\nnan = 0.0 / 0.0 # or Float::NAN\n\nexpression = [\n \"1.0 / 0.0\", \"-1.0 / 0.0\", \"0.0 / 0.0\", \"- 0.0\",\n \"inf + 1\", \"5 - inf\", \"inf * 5\", \"inf / 5\", \"inf * 0\",\n \"1.0 / inf\", \"-1.0 / inf\", \"inf + inf\", \"inf - inf\",\n \"inf * inf\", \"inf / inf\", \"inf * 0.0\", \" 0 < inf\", \"inf == inf\",\n \"nan + 1\", \"nan * 5\", \"nan - nan\", \"nan * inf\", \"- nan\",\n \"nan == nan\", \"nan > 0\", \"nan < 0\", \"nan == 0\", \"nan <=> 0.0\", \"0.0 == -0.0\",\n]\n\nexpression.each do |exp|\n puts \"%15s => %p\" % [exp, eval(exp)]\nend"} {"title": "FASTA format", "language": "Ruby", "task": "In FASTA. \n\nA FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.\n\n\n;Task:\nWrite a program that reads a FASTA file such as:\n\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n", "solution": "def fasta_format(strings)\n out, text = [], \"\"\n strings.split(\"\\n\").each do |line|\n if line[0] == '>'\n out << text unless text.empty?\n text = line[1..-1] + \": \"\n else\n text << line\n end\n end\n out << text unless text.empty?\nend\n\ndata = <<'EOS'\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\nEOS\n\nputs fasta_format(data)"} {"title": "Factorial primes", "language": "Ruby", "task": "Definition\nA factorial.\n\nIn other words a non-negative integer '''n''' corresponds to a factorial prime if either '''n'''! - 1 or '''n'''! + 1 is prime. \n\n;Examples\n4 corresponds to the factorial prime 4! - 1 = 23.\n\n5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime.\n\n;Task\nFind and show here the first 10 factorial primes. As well as the prime itself show the factorial number '''n''' to which it corresponds and whether 1 is to be added or subtracted. \n\nAs 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!.\n\n;Stretch\nIf your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes.\n\nAs it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function.\n\nIf a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has.\n\n;Reference\n* OEIS:A088054 - Factorial primes\n\n;Related task\n* Sequence of primorial primes\n\n", "solution": "require 'openssl'\n\nfactorial_primes = Enumerator.new do |y|\n fact = 1\n (1..).each do |i|\n fact *= i\n y << [i, \"- 1\", fact - 1] if OpenSSL::BN.new(fact - 1).prime?\n y << [i, \"+ 1\", fact + 1] if OpenSSL::BN.new(fact + 1).prime?\n end\nend\n\nfactorial_primes.first(30).each do |a|\n s = a.last.to_s\n if s.size > 40 then \n puts \"%d! %s = \" % a.first(2) + \"#{s[0,20]}...#{s[-20,20]}\"\n else\n puts \"%d! %s = %d\" % a \n end\nend\n"} {"title": "Factorions", "language": "Ruby", "task": "Definition:\nA factorion is a natural number that equals the sum of the factorials of its digits. \n\n\n;Example: \n'''145''' is a factorion in base '''10''' because:\n\n 1! + 4! + 5! = 1 + 24 + 120 = 145 \n\n\n\nIt can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''.\n\n\n;Task:\nWrite a program in your language to demonstrate, by calculating and printing out the factorions, that:\n:* There are '''3''' factorions in base '''9'''\n:* There are '''4''' factorions in base '''10'''\n:* There are '''5''' factorions in base '''11''' \n:* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''')\n\n\n;See also:\n:* '''Wikipedia article'''\n:* '''OEIS:A014080 - Factorions in base 10'''\n:* '''OEIS:A193163 - Factorions in base n'''\n\n", "solution": "def factorion?(n, base)\n n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n \nend\n\n(9..12).each do |base|\n puts \"Base #{base} factorions: #{(1..1_500_000).select{|n| factorion?(n, base)}.join(\" \")} \"\nend\n"} {"title": "Fairshare between two and more", "language": "Ruby from C", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "def turn(base, n)\n sum = 0\n while n != 0 do\n rem = n % base\n n = n / base\n sum = sum + rem\n end\n return sum % base\nend\n\ndef fairshare(base, count)\n print \"Base %2d: \" % [base]\n for i in 0 .. count - 1 do\n t = turn(base, i)\n print \" %2d\" % [t]\n end\n print \"\\n\"\nend\n\ndef turnCount(base, count)\n cnt = Array.new(base, 0)\n\n for i in 0 .. count - 1 do\n t = turn(base, i)\n cnt[t] = cnt[t] + 1\n end\n\n minTurn = base * count\n maxTurn = -1\n portion = 0\n for i in 0 .. base - 1 do\n if cnt[i] > 0 then\n portion = portion + 1\n end\n if cnt[i] < minTurn then\n minTurn = cnt[i]\n end\n if cnt[i] > maxTurn then\n maxTurn = cnt[i]\n end\n end\n\n print \" With %d people: \" % [base]\n if 0 == minTurn then\n print \"Only %d have a turn\\n\" % portion\n elsif minTurn == maxTurn then\n print \"%d\\n\" % [minTurn]\n else\n print \"%d or %d\\n\" % [minTurn, maxTurn]\n end\nend\n\ndef main\n fairshare(2, 25)\n fairshare(3, 25)\n fairshare(5, 25)\n fairshare(11, 25)\n\n puts \"How many times does each get a turn in 50000 iterations?\"\n turnCount(191, 50000)\n turnCount(1377, 50000)\n turnCount(49999, 50000)\n turnCount(50000, 50000)\n turnCount(50001, 50000)\nend\n\nmain()"} {"title": "Fairshare between two and more", "language": "Ruby from Sidef", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "def fairshare(base, upto) = (0...upto).map{|n| n.digits(base).sum % base}\n\nupto = 25\n[2, 3, 5, 11].each{|b| puts\"#{'%2d' % b}: \" + \" %2d\"*upto % fairshare(b, upto)}\n"} {"title": "Farey sequence", "language": "Ruby from Python", "task": "The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.\n\nThe ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. \n\n\nEach Farey sequence:\n:::* starts with the value '''0''' (zero), denoted by the fraction \\frac{0}{1} \n:::* ends with the value '''1''' (unity), denoted by the fraction \\frac{1}{1}.\n\n\nThe Farey sequences of orders '''1''' to '''5''' are:\n\n:::: {\\bf\\it{F}}_1 = \\frac{0}{1}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_2 = \\frac{0}{1}, \\frac{1}{2}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_3 = \\frac{0}{1}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_4 = \\frac{0}{1}, \\frac{1}{4}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{3}{4}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_5 = \\frac{0}{1}, \\frac{1}{5}, \\frac{1}{4}, \\frac{1}{3}, \\frac{2}{5}, \\frac{1}{2}, \\frac{3}{5}, \\frac{2}{3}, \\frac{3}{4}, \\frac{4}{5}, \\frac{1}{1}\n\n;Task\n* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).\n* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.\n* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length (the number of fractions) of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 x n2 / \\pi2 \n\n;See also:\n* OEIS sequence A006842 numerators of Farey series of order 1, 2, *** \n* OEIS sequence A006843 denominators of Farey series of order 1, 2, *** \n* OEIS sequence A005728 number of fractions in Farey series of order n \n* MathWorld entry Farey sequence\n* Wikipedia entry Farey sequence\n\n", "solution": "def farey(n, length=false)\n if length\n (n*(n+3))/2 - (2..n).sum{|k| farey(n/k, true)}\n else\n (1..n).each_with_object([]){|k,a|(0..k).each{|m|a << Rational(m,k)}}.uniq.sort\n end\nend\n\nputs 'Farey sequence for order 1 through 11 (inclusive):'\nfor n in 1..11\n puts \"F(#{n}): \" + farey(n).join(\", \")\nend\nputs 'Number of fractions in the Farey sequence:'\nfor i in (100..1000).step(100)\n puts \"F(%4d) =%7d\" % [i, farey(i, true)]\nend"} {"title": "Fast Fourier transform", "language": "Ruby", "task": "Calculate the FFT (Fast Fourier Transform) of an input sequence.\n\nThe most general case allows for complex numbers at the input \nand results in a sequence of equal length, again of complex numbers. \nIf you need to restrict yourself to real numbers, the output should \nbe the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. \n\nThe classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "def fft(vec)\n return vec if vec.size <= 1\n evens_odds = vec.partition.with_index{|_,i| i.even?}\n evens, odds = evens_odds.map{|even_odd| fft(even_odd)*2} \n evens.zip(odds).map.with_index do |(even, odd),i|\n even + odd * Math::E ** Complex(0, -2 * Math::PI * i / vec.size)\n end\nend\n \nfft([1,1,1,1,0,0,0,0]).each{|c| puts \"%9.6f %+9.6fi\" % c.rect}"} {"title": "Feigenbaum constant calculation", "language": "Ruby from C#", "task": "Calculate the Feigenbaum constant. \n\n\n;See:\n:* Details in the Wikipedia article: Feigenbaum constant.\n\n", "solution": "def main\n maxIt = 13\n maxItJ = 10\n a1 = 1.0\n a2 = 0.0\n d1 = 3.2\n puts \" i d\"\n for i in 2 .. maxIt\n a = a1 + (a1 - a2) / d1\n for j in 1 .. maxItJ\n x = 0.0\n y = 0.0\n for k in 1 .. 1 << i\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n end\n a = a - x / y\n end\n d = (a1 - a2) / (a - a1)\n print \"%2d %.8f\\n\" % [i, d]\n d1 = d\n a2 = a1\n a1 = a\n end\nend\n\nmain()"} {"title": "Fibonacci n-step number sequences", "language": "Ruby", "task": "These number series are an expansion of the ordinary [[Fibonacci sequence]] where:\n# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2\n# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3\n# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...\n# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \\sum_{i=1}^{(n)} {F_{k-i}^{(n)}}\n\nFor small values of n, Greek numeric prefixes are sometimes used to individually name each series.\n\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Fibonacci n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Series name !! Values\n|-\n| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\n|-\n| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\n|-\n| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\n|-\n| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\n|-\n| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\n|-\n| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\n|-\n| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\n|-\n| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\n|-\n| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n|}\n\nAllied sequences can be generated where the initial values are changed:\n: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.\n\n\n\n;Task:\n# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\n\n;Related tasks:\n* [[Fibonacci sequence]]\n* Wolfram Mathworld\n* [[Hofstadter Q sequence]]\n* [[Leonardo numbers]]\n\n\n;Also see:\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers\n\n", "solution": "def anynacci(start_sequence, count)\n n = start_sequence.length # Get the n-step for the type of fibonacci sequence\n result = start_sequence.dup # Create a new result array with the values copied from the array that was passed by reference\n (count-n).times do # Loop for the remaining results up to count\n result << result.last(n).sum # Get the last n element from result and append its total to Array\n end\n result \nend\n \nnaccis = { lucas: [2,1],\n fibonacci: [1,1],\n tribonacci: [1,1,2],\n tetranacci: [1,1,2,4],\n pentanacci: [1,1,2,4,8],\n hexanacci: [1,1,2,4,8,16],\n heptanacci: [1,1,2,4,8,16,32],\n octonacci: [1,1,2,4,8,16,32,64],\n nonanacci: [1,1,2,4,8,16,32,64,128],\n decanacci: [1,1,2,4,8,16,32,64,128,256] }\n\nnaccis.each {|name, seq| puts \"%12s : %p\" % [name, anynacci(seq, 15)]}"} {"title": "Fibonacci word", "language": "Ruby", "task": "The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:\n\n Define F_Word1 as '''1'''\n Define F_Word2 as '''0'''\n Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''\n Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2\n\n\n;Task:\nPerform the above steps for n = 37.\n\nYou may display the first few but not the larger values of n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for F_Words '''1''' to '''37''' which shows:\n::* The number of characters in the word\n::* The word's [[Entropy]]\n\n\n;Related tasks: \n* Fibonacci word/fractal\n* [[Entropy]]\n* [[Entropy/Narcissist]]\n\n", "solution": "#encoding: ASCII-8BIT\n\ndef entropy(s)\n counts = Hash.new(0.0)\n s.each_char { |c| counts[c] += 1 }\n leng = s.length\n \n counts.values.reduce(0) do |entropy, count|\n freq = count / leng\n entropy - freq * Math.log2(freq)\n end\nend\n\nn_max = 37\nwords = ['1', '0']\n\nfor n in words.length ... n_max\n words << words[-1] + words[-2]\nend\n\nputs '%3s %9s %15s %s' % %w[N Length Entropy Fibword]\nwords.each.with_index(1) do |word, i|\n puts '%3i %9i %15.12f %s' % [i, word.length, entropy(word), word.length<60 ? word : '']\nend"} {"title": "File extension is in extensions list", "language": "Ruby", "task": "Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the [[Extract file extension]] task.\n\n\n;Related tasks: \n* [[Extract file extension]]\n* [[String matching]]\n\n", "solution": "def is_ext(filename, extensions)\n if filename.respond_to?(:each) \n filename.each do |fn|\n is_ext(fn, extensions)\n end\n else\n fndc = filename.downcase\n extensions.each do |ext|\n bool = fndc.end_with?(?. + ext.downcase)\n puts \"%20s : %s\" % [filename, bool] if bool\n end\n end\nend\n"} {"title": "Find Chess960 starting position identifier", "language": "Ruby", "task": "Starting Position Identifier number (\"SP-ID\"), and generate the corresponding position. \n\n;Task:\nThis task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array '''QNRBBNKR''' (or '''''' or ''''''), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.\n\nYou may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.\n\n;Algorithm:\n\nThe derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).\n\n1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0='''NN---''', 1='''N-N--''', 2='''N--N-''', 3='''N---N''', 4='''-NN--''', etc; our pair is combination number 5. Call this number N. '''N=5'''\n\n2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, '''Q=2'''.\n\n3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 ('''D=1'''), and the light bishop is on square 2 ('''L=2''').\n\n4. Then the position number is given by '''4(4(6N + Q)+D)+L''', which reduces to '''96N + 16Q + 4D + L'''. In our example, that's 96x5 + 16x2 + 4x1 + 2 = 480 + 32 + 4 + 2 = 518.\n\nNote that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.\n\n RQNBBKRN = 601\n RNQBBKRN = 617\n\n", "solution": "CHESS_PIECES = %w<\u2656\u2658\u2657\u2655\u2654 \u265c\u265e\u265d\u265b\u265a>\ndef chess960_to_spid(pos)\n start_str = pos.tr(CHESS_PIECES.join, \"RNBQKRNBQK\")\n #1 knights score\n s = start_str.delete(\"QB\")\n n = [0,1,2,3,4].combination(2).to_a.index( [s.index(\"N\"), s.rindex(\"N\")] )\n #2 queen score\n q = start_str.delete(\"B\").index(\"Q\")\n #3 bishops\n bs = start_str.index(\"B\"), start_str.rindex(\"B\")\n d = bs.detect(&:even?).div(2)\n l = bs.detect(&:odd? ).div(2)\n\n 96*n + 16*q + 4*d + l\nend\n\n%w.each_with_index do |array, i|\n pieces = array.tr(\"RNBQK\", CHESS_PIECES[i%2])\n puts \"#{pieces} (#{array}): #{chess960_to_spid array}\"\nend\n"} {"title": "Find duplicate files", "language": "Ruby", "task": "In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. \n\n\n;Task:\nCreate a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.\n\nThe program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data. \n\nSpecify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements. \n\nIdentify hard links (filenames referencing the same content) in the output if applicable for the filesystem. \n\nFor extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.\n\n", "solution": "require 'digest/md5'\n\ndef find_duplicate_files(dir)\n puts \"\\nDirectory : #{dir}\"\n Dir.chdir(dir) do\n file_size = Dir.foreach('.').select{|f| FileTest.file?(f)}.group_by{|f| File.size(f)}\n file_size.each do |size, files|\n next if files.size==1\n files.group_by{|f| Digest::MD5.file(f).to_s}.each do |md5,fs|\n next if fs.size==1\n puts \" --------------------------------------------\"\n fs.each{|file| puts \" #{File.mtime(file)} #{size} #{file}\"}\n end\n end\n end\nend\n\nfind_duplicate_files(\"/Windows/System32\")"} {"title": "Find if a point is within a triangle", "language": "Ruby from Go", "task": "Find if a point is within a triangle.\n\n\n;Task:\n \n::* Assume points are on a plane defined by (x, y) real number coordinates.\n\n::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. \n\n::* You may use any algorithm. \n\n::* Bonus: explain why the algorithm you chose works.\n\n\n;Related tasks:\n* [[Determine_if_two_triangles_overlap]]\n\n\n;Also see:\n:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]\n:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]\n:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]\n:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]\n\n", "solution": "EPS = 0.001\nEPS_SQUARE = EPS * EPS\n\ndef side(x1, y1, x2, y2, x, y)\n return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1)\nend\n\ndef naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n checkSide1 = side(x1, y1, x2, y2, x, y) >= 0\n checkSide2 = side(x2, y2, x3, y3, x, y) >= 0\n checkSide3 = side(x3, y3, x1, y1, x, y) >= 0\n return checkSide1 && checkSide2 && checkSide3\nend\n\ndef pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)\n xMin = [x1, x2, x3].min - EPS\n xMax = [x1, x2, x3].max + EPS\n yMin = [y1, y2, y3].min - EPS\n yMax = [y1, y2, y3].max + EPS\n return !(x < xMin || xMax < x || y < yMin || yMax < y)\nend\n\ndef distanceSquarePointToSegment(x1, y1, x2, y2, x, y)\n p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)\n dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength\n if dotProduct < 0 then\n return (x - x1) * (x - x1) + (y - y1) * (y - y1)\n end\n if dotProduct <= 1 then\n p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y)\n return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength\n end\n return (x - x2) * (x - x2) + (y - y2) * (y - y2)\nend\n\ndef accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) then\n return false\n end\n if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) then\n return true\n end\n if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then\n return true\n end\n if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then\n return true\n end\n if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then\n return true\n end\n return false\nend\n\ndef main\n pts = [[0, 0], [0, 1], [3, 1]]\n tri = [[1.5, 2.4], [5.1, -3.1], [-3.8, 1.2]]\n print \"Triangle is \", tri, \"\\n\"\n x1, y1 = tri[0][0], tri[0][1]\n x2, y2 = tri[1][0], tri[1][1]\n x3, y3 = tri[2][0], tri[2][1]\n for pt in pts\n x, y = pt[0], pt[1]\n within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n print \"Point \", pt, \" is within triangle? \", within, \"\\n\"\n end\n print \"\\n\"\n\n tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [25.0, 100.0 / 9.0]]\n print \"Triangle is \", tri, \"\\n\"\n x1, y1 = tri[0][0], tri[0][1]\n x2, y2 = tri[1][0], tri[1][1]\n x3, y3 = tri[2][0], tri[2][1]\n x = x1 + (3.0 / 7.0) * (x2 - x1)\n y = y1 + (3.0 / 7.0) * (y2 - y1)\n pt = [x, y]\n within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n print \"Point \", pt, \" is within triangle? \", within, \"\\n\"\n print \"\\n\"\n\n tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [-12.5, 100.0 / 6.0]]\n print \"Triangle is \", tri, \"\\n\"\n x3, y3 = tri[2][0], tri[2][1]\n within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n print \"Point \", pt, \" is within triangle? \", within, \"\\n\"\nend\n\nmain()"} {"title": "Find palindromic numbers in both binary and ternary bases", "language": "Ruby", "task": "* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':\n:::* base 2\n:::* base 3\n* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.\n* Optionally, show the decimal number found in its binary and ternary form.\n* Show all output here.\n\n\nIt's permissible to assume the first two numbers and simply list them.\n\n\n;See also\n* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.\n\n", "solution": "pal23 = Enumerator.new do |y|\n y << 0\n y << 1\n for i in 1 .. 1.0/0.0 # 1.step do |i| (Ruby 2.1+)\n n3 = i.to_s(3)\n n = (n3 + \"1\" + n3.reverse).to_i(3)\n n2 = n.to_s(2)\n y << n if n2.size.odd? and n2 == n2.reverse\n end\nend\n\nputs \" decimal ternary binary\"\n6.times do |i|\n n = pal23.next\n puts \"%2d: %12d %s %s\" % [i, n, n.to_s(3).center(25), n.to_s(2).center(39)]\nend"} {"title": "Find the intersection of a line with a plane", "language": "Ruby from C#", "task": "Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.\n\n\n;Task:\nFind the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].\n\n", "solution": "require \"matrix\"\n\ndef intersectPoint(rayVector, rayPoint, planeNormal, planePoint)\n diff = rayPoint - planePoint\n prod1 = diff.dot planeNormal\n prod2 = rayVector.dot planeNormal\n prod3 = prod1 / prod2\n return rayPoint - rayVector * prod3\nend\n\ndef main\n rv = Vector[0.0, -1.0, -1.0]\n rp = Vector[0.0, 0.0, 10.0]\n pn = Vector[0.0, 0.0, 1.0]\n pp = Vector[0.0, 0.0, 5.0]\n ip = intersectPoint(rv, rp, pn, pp)\n puts \"The ray intersects the plane at %s\" % [ip]\nend\n\nmain()"} {"title": "Find the intersection of two lines", "language": "Ruby", "task": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]\n\n;Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though (4,0) and (6,10) . \nThe 2nd line passes though (0,3) and (10,7) .\n\n", "solution": "Point = Struct.new(:x, :y)\n\nclass Line\n attr_reader :a, :b\n\n def initialize(point1, point2)\n @a = (point1.y - point2.y).fdiv(point1.x - point2.x)\n @b = point1.y - @a*point1.x\n end\n\n def intersect(other)\n return nil if @a == other.a\n x = (other.b - @b).fdiv(@a - other.a)\n y = @a*x + @b\n Point.new(x,y)\n end\n\n def to_s\n \"y = #{@a}x #{@b.positive? ? '+' : '-'} #{@b.abs}\"\n end\n\nend\n\nl1 = Line.new(Point.new(4, 0), Point.new(6, 10))\nl2 = Line.new(Point.new(0, 3), Point.new(10, 7))\n\nputs \"Line #{l1} intersects line #{l2} at #{l1.intersect(l2)}.\"\n"} {"title": "Find the last Sunday of each month", "language": "Ruby", "task": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n\n;Related tasks\n* [[Day of the week]]\n* [[Five weekends]]\n* [[Last Friday of each month]]\n\n", "solution": "require 'date'\n\ndef last_sundays_of_year(year = Date.today.year)\n (1..12).map do |month|\n d = Date.new(year, month, -1) # -1 means \"last\".\n d - d.wday\n end\nend\n\nputs last_sundays_of_year(2013)"} {"title": "Find the missing permutation", "language": "Ruby 2.0+", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "given = %w{\n ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA\n CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB\n}\n \nall = given[0].chars.permutation.collect(&:join)\n \nputs \"missing: #{all - given}\""} {"title": "First-class functions/Use numbers analogously", "language": "Ruby", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": "multiplier = proc {|n1, n2| proc {|m| n1 * n2 * m}}\nnumlist = [x=2, y=4, x+y]\ninvlist = [0.5, 0.25, 1.0/(x+y)]\np numlist.zip(invlist).map {|n, invn| multiplier[invn, n][0.5]}\n# => [0.5, 0.5, 0.5]"} {"title": "First perfect square in base n with n unique digits", "language": "Ruby", "task": "Find the first perfect square in a given base '''N''' that has at least '''N''' digits and\nexactly '''N''' ''significant unique'' digits when expressed in base '''N'''.\n\nE.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').\n\nYou may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.\n\n;Task\n\n* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.\n\n* (optional) Do the same for bases '''13''' through '''16'''.\n\n* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)\n\n\n;See also:\n\n;* OEIS A260182: smallest square that is pandigital in base n.\n\n;Related task\n\n;* [[Casting out nines]]\n\n", "solution": "DIGITS = \"1023456789abcdefghijklmnopqrstuvwxyz\"\n\n2.upto(16) do |n|\n start = Integer.sqrt( DIGITS[0,n].to_i(n) )\n res = start.step.detect{|i| (i*i).digits(n).uniq.size == n }\n puts \"Base %2d:%10s\u00b2 = %-14s\" % [n, res.to_s(n), (res*res).to_s(n)]\nend\n"} {"title": "First power of 2 that has leading decimal digits of 12", "language": "Ruby from C", "task": "(This task is taken from a ''Project Euler'' problem.)\n\n(All numbers herein are expressed in base ten.)\n\n\n'''27 = 128''' and '''7''' is\nthe first power of '''2''' whose leading decimal digits are '''12'''.\n\nThe next power of '''2''' whose leading decimal digits\nare '''12''' is '''80''',\n'''280 = 1208925819614629174706176'''.\n\n\nDefine ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest\nvalue of ''' ''j'' ''' such that the base ten representation\nof '''2''j''''' begins with the digits of ''' ''L'' '''.\n\n So ''p''(12, 1) = 7 and\n ''p''(12, 2) = 80\n\n\nYou are also given that:\n ''p''(123, 45) = 12710\n\n\n;Task:\n::* find: \n:::::* ''' ''p''(12, 1) ''' \n:::::* ''' ''p''(12, 2) ''' \n:::::* ''' ''p''(123, 45) ''' \n:::::* ''' ''p''(123, 12345) ''' \n:::::* ''' ''p''(123, 678910) ''' \n::* display the results here, on this page.\n\n", "solution": "def p(l, n)\n test = 0\n logv = Math.log(2.0) / Math.log(10.0)\n factor = 1\n loopv = l\n while loopv > 10 do\n factor = factor * 10\n loopv = loopv / 10\n end\n while n > 0 do\n test = test + 1\n val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor\n if val == l then\n n = n - 1\n end\n end\n return test\nend\n\ndef runTest(l, n)\n print \"P(%d, %d) = %d\\n\" % [l, n, p(l, n)]\nend\n\nrunTest(12, 1)\nrunTest(12, 2)\nrunTest(123, 45)\nrunTest(123, 12345)\nrunTest(123, 678910)"} {"title": "Fivenum", "language": "Ruby from Perl", "task": "Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, there are variations among statistical packages for the whiskers.\n\n", "solution": "def fivenum(array)\n sorted_arr = array.sort\n n = array.size\n n4 = (((n + 3).to_f / 2.to_f) / 2.to_f).floor\n d = Array.[](1, n4, ((n.to_f + 1) / 2).to_i, n + 1 - n4, n)\n sum_array = []\n (0..4).each do |e| # each loops have local scope, for loops don't\n index_floor = (d[e] - 1).floor\n index_ceil = (d[e] - 1).ceil\n sum_array.push(0.5 * (sorted_arr[index_floor] + sorted_arr[index_ceil]))\n end\n sum_array\nend\n\ntest_array = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43]\ntukey_array = fivenum(test_array)\np tukey_array\ntest_array = [36, 40, 7, 39, 41, 15]\ntukey_array = fivenum(test_array)\np tukey_array\ntest_array = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,\n 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,\n 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,\n 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]\ntukey_array = fivenum(test_array)\np tukey_array\n"} {"title": "Fixed length records", "language": "Ruby", "task": "Fixed length read/write\n\nBefore terminals, computers commonly used punch card readers or paper tape input.\n\nA common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.\n\nThese input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.\n\nThese devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).\n\n;Task:\nWrite a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. \n\nSamples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.\n\n'''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.\n\nThese fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''.\n\n;Sample data:\nTo create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size.\n\nLine 1...1.........2.........3.........4.........5.........6.........7.........8\nLine 2\nLine 3\nLine 4\n\nLine 6\nLine 7\n Indented line 8............................................................\nLine 9 RT MARGIN\nprompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input.\n\nprompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines.\n\n\n;Bonus round:\nForth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).\n\nWrite a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.\n\nAlso demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.\n\nThe COBOL example uses forth.txt and forth.blk filenames.\n\n", "solution": "open(\"outfile.dat\", \"w\") do |out_f|\n open(\"infile.dat\") do |in_f| \n while record = in_f.read(80) \n out_f << record.reverse\n end\n end\nend # both files automatically closed \n"} {"title": "Flatten a list", "language": "Ruby", "task": "Write a function to flatten the nesting in an arbitrary list of values. \n\nYour program should work on the equivalent of this list:\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\nWhere the correct result would be the list:\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n;Related task:\n* [[Tree traversal]]\n\n", "solution": "p flatten_once = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten(1)\n# => [1, 2, [3, 4], 5, [[]], [[6]], 7, 8]\n"} {"title": "Flipping bits game", "language": "Ruby", "task": "The game:\nGiven an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.\n\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered \ncolumns at once (as one move).\n\nIn an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.\n\n\n;Task:\nCreate a program to score for the Flipping bits game.\n# The game should create an original random target configuration and a starting configuration.\n# Ensure that the starting position is ''never'' the target position.\n# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).\n# The number of moves taken so far should be shown.\n\n\nShow an example of a short game here, on this page, for a '''3x3''' array of bits.\n\n", "solution": "class FlipBoard\n def initialize(size)\n raise ArgumentError.new(\"Invalid board size: #{size}\") if size < 2\n \n @size = size\n @board = Array.new(size**2, 0)\n \n randomize_board\n loop do\n @target = generate_target\n break unless solved?\n end \n \n # these are used for validating user input\n @columns = [*'a'...('a'.ord+@size).chr]\n @rows = (1..@size).map(&:to_s)\n end\n \n ############################################################\n \n def play\n moves = 0\n puts \"your target:\", target\n \n until solved? \n puts \"\", \"move #{moves}:\", self\n print \"Row/column to flip: \"\n ans = $stdin.gets.strip\n \n if @columns.include? ans\n flip_column @columns.index(ans)\n moves += 1\n elsif @rows.include? ans\n flip_row @rows.index(ans)\n moves += 1\n else\n puts \"invalid input: \" + ans\n end\n end\n \n puts \"\", \"you solved the game in #{moves} moves\", self\n end\n \n # the target formation as a string\n def target\n format_array @target\n end\n \n # the current formation as a string\n def to_s\n format_array @board\n end\n \n ############################################################\n private\n \n def solved?\n @board == @target\n end\n \n # flip a random number of bits on the board\n def randomize_board\n (@size + rand(@size)).times do\n flip_bit rand(@size), rand(@size)\n end\n end\n \n # generate a random number of flip_row/flip_column calls\n def generate_target\n orig_board = @board.clone\n (@size + rand(@size)).times do \n rand(2).zero? ? flip_row( rand(@size) ) : flip_column( rand(@size) )\n end\n target, @board = @board, orig_board\n target\n end\n \n def flip_row(row)\n @size.times {|col| flip_bit(row, col)}\n end\n \n def flip_column(col)\n @size.times {|row| flip_bit(row, col)}\n end\n \n def flip_bit(row, col)\n @board[@size * row + col] ^= 1\n end\n \n def format_array(ary)\n str = \" \" + @columns.join(\" \") + \"\\n\"\n @size.times do |row|\n str << \"%2s \" % @rows[row] + ary[@size*row, @size].join(\" \") + \"\\n\"\n end\n str\n end\nend\n\n######################################################################\nbegin\n FlipBoard.new(ARGV.shift.to_i).play\nrescue => e\n puts e.message\nend"} {"title": "Floyd's triangle", "language": "Ruby", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "def floyd(rows)\n max = (rows * (rows + 1)) / 2\n widths = ((max - rows + 1)..max).map {|n| n.to_s.length + 1}\n n = 0\n rows.times do |r|\n puts (0..r).map {|i| n += 1; \"%#{widths[i]}d\" % n}.join\n end\nend\n\nfloyd(5)\nfloyd(14)"} {"title": "Four bit adder", "language": "Ruby", "task": "\"''Simulate''\" a four-bit adder.\n \nThis design can be realized using four 1-bit full adders. \nEach of these 1-bit full adders can be built with two gate. ; \n\nFinally a half adder can be made using an ''xor'' gate and an ''and'' gate. \n\nThe ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.\n\n'''Not''', '''or''' and '''and''', the only allowed \"gates\" for the task, can be \"imitated\" by using the bitwise operators of your language. \n\nIf there is not a ''bit type'' in your language, to be sure that the ''not'' does not \"invert\" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other \"constructive blocks\", in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \n! (A half adder) \n! (A full adder) \n! (A 4-bit adder) \n|-\n|Xor gate done with ands, ors and nots\n|A half adder\n|A full adder\n|A 4-bit adder\n|}\n\n\n\nSolutions should try to be as descriptive as possible, making it as easy as possible to identify \"connections\" between higher-order \"blocks\". \n\nIt is not mandatory to replicate the syntax of higher-order blocks in the atomic \"gate\" blocks, i.e. basic \"gate\" operations can be performed as usual bitwise operations, or they can be \"wrapped\" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.\n\nTo test the implementation, show the sum of two four-bit numbers (in binary).\n\n\n", "solution": "# returns pair [sum, carry]\ndef four_bit_adder(a, b)\n a_bits = binary_string_to_bits(a,4)\n b_bits = binary_string_to_bits(b,4)\n \n s0, c0 = full_adder(a_bits[0], b_bits[0], 0)\n s1, c1 = full_adder(a_bits[1], b_bits[1], c0)\n s2, c2 = full_adder(a_bits[2], b_bits[2], c1)\n s3, c3 = full_adder(a_bits[3], b_bits[3], c2)\n \n [bits_to_binary_string([s0, s1, s2, s3]), c3.to_s]\nend\n\n# returns pair [sum, carry]\ndef full_adder(a, b, c0)\n s, c = half_adder(c0, a)\n s, c1 = half_adder(s, b)\n [s, _or(c,c1)]\nend\n\n# returns pair [sum, carry]\ndef half_adder(a, b)\n [xor(a, b), _and(a,b)]\nend\n\ndef xor(a, b)\n _or(_and(a, _not(b)), _and(_not(a), b))\nend\n\n# \"and\", \"or\" and \"not\" are Ruby keywords\ndef _and(a, b) a & b end\ndef _or(a, b) a | b end\ndef _not(a) ~a & 1 end\n\ndef int_to_binary_string(n, length)\n \"%0#{length}b\" % n\nend\n\ndef binary_string_to_bits(s, length)\n (\"%#{length}s\" % s).reverse.chars.map(&:to_i)\nend\n\ndef bits_to_binary_string(bits)\n bits.map(&:to_s).reverse.join\nend\n\nputs \" A B A B C S sum\" \n0.upto(15) do |a|\n 0.upto(15) do |b|\n bin_a = int_to_binary_string(a, 4)\n bin_b = int_to_binary_string(b, 4)\n sum, carry = four_bit_adder(bin_a, bin_b)\n puts \"%2d + %2d = %s + %s = %s %s = %2d\" %\n [a, b, bin_a, bin_b, carry, sum, (carry + sum).to_i(2)]\n end\nend"} {"title": "Four is magic", "language": "Ruby", "task": "Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* [[Four is the number of_letters in the ...]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Summarize and say sequence]]\n:* [[Spelling of ordinal numbers]]\n:* [[De Bruijn sequences]]\n\n", "solution": "module NumberToWord\n \n NUMBERS = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3\n 1 => 'one',\n 2 => 'two',\n 3 => 'three',\n 4 => 'four',\n 5 => 'five',\n 6 => 'six',\n 7 => 'seven',\n 8 => 'eight',\n 9 => 'nine',\n 10 => 'ten',\n 11 => 'eleven',\n 12 => 'twelve',\n 13 => 'thirteen',\n 14 => 'fourteen',\n 15 => 'fifteen',\n 16 => 'sixteen',\n 17 => 'seventeen',\n 18 => 'eighteen',\n 19 => 'nineteen',\n 20 => 'twenty',\n 30 => 'thirty',\n 40 => 'forty',\n 50 => 'fifty',\n 60 => 'sixty',\n 70 => 'seventy',\n 80 => 'eighty',\n 90 => 'ninety',\n 100 => 'hundred',\n 1000 => 'thousand',\n 10 ** 6 => 'million',\n 10 ** 9 => 'billion',\n 10 ** 12 => 'trillion',\n 10 ** 15 => 'quadrillion',\n 10 ** 18 => 'quintillion',\n 10 ** 21 => 'sextillion',\n 10 ** 24 => 'septillion',\n 10 ** 27 => 'octillion',\n 10 ** 30 => 'nonillion',\n 10 ** 33 => 'decillion'}.reverse_each.to_h\n \n refine Integer do\n def to_english\n return 'zero' if i.zero?\n words = self < 0 ? ['negative'] : []\n i = self.abs\n NUMBERS.each do |k, v|\n if k <= i then\n times = i/k\n words << times.to_english if k >= 100\n words << v\n i -= times * k\n end\n return words.join(\" \") if i.zero?\n end\n end\n end\n \nend\n \nusing NumberToWord\n \ndef magic4(n)\n words = []\n until n == 4\n s = n.to_english\n n = s.size\n words << \"#{s} is #{n.to_english}\"\n end\n words << \"four is magic.\"\n words.join(\", \").capitalize\nend\n \n[0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each{|n| puts magic4(n) }\n "} {"title": "Fusc sequence", "language": "Ruby", "task": "Definitions:\nThe '''fusc''' integer sequence is defined as:\n::* fusc(0) = 0\n::* fusc(1) = 1\n::* for '''n'''>1, the '''n'''th term is defined as:\n::::* if '''n''' is even; fusc(n) = fusc(n/2)\n::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).\n\n\n\n;An observation:\n:::::* fusc(A) = fusc(B)\n\nwhere '''A''' is some non-negative integer expressed in binary, and\nwhere '''B''' is the binary value of '''A''' reversed.\n\n\n\nFusc numbers are also known as:\n::* fusc function (named by Dijkstra, 1982)\n::* Stern's Diatomic series (although it starts with unity, not zero)\n::* Stern-Brocot sequence (although it starts with unity, not zero)\n\n\n\n;Task:\n::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.\n::* show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* show all numbers with commas (if appropriate).\n::* show all output here.\n\n\n;Related task:\n::* RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* the MathWorld entry: Stern's Diatomic Series.\n::* the OEIS entry: A2487.\n\n", "solution": "fusc = Enumerator.new do |y|\n y << 0\n y << 1\n arr = [0,1]\n 2.step do |n|\n res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2]\n y << res\n arr << res\n end\nend\n\nfusc_max_digits = Enumerator.new do |y|\n cur_max, cur_exp = 0, 0\n 0.step do |i|\n f = fusc.next\n if f >= cur_max\n cur_exp += 1\n cur_max = 10**cur_exp\n y << [i, f]\n end\n end\nend\n\nputs fusc.take(61).join(\" \")\nfusc_max_digits.take(6).each{|pair| puts \"%15s : %s\" % pair }\n"} {"title": "Gapful numbers", "language": "Ruby", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''187'''. \n\n\nAbout 7.46% of positive integers are ''gapful''. \n\n\n;Task:\n:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page\n:* Show the first '''30''' gapful numbers\n:* Show the first '''15''' gapful numbers >= '''1,000,000'''\n:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''\n\n\n;Related tasks:\n:* Harshad or Niven series.\n:* palindromic gapful numbers.\n:* largest number divisible by its digits.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n:* numbersaplenty gapful numbers\n\n", "solution": "class Integer\n def gapful?\n a = digits\n self % (a.last*10 + a.first) == 0\n end\nend\n\nspecs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}\n\nspecs.each do |start, num|\n puts \"first #{num} gapful numbers >= #{start}:\"\n p (start..).lazy.select(&:gapful?).take(num).to_a\nend\n"} {"title": "Gauss-Jordan matrix inversion", "language": "Ruby", "task": "Invert matrix '''A''' using Gauss-Jordan method.\n\n'''A''' being an '''n''' x '''n''' matrix.\n\n", "solution": "require 'matrix'\n\nm = Matrix[[-1, -2, 3, 2],\n [-4, -1, 6, 2],\n [ 7, -8, 9, 1],\n [ 1, -2, 1, 3]]\n\npp m.inv.row_vectors\n"} {"title": "Gaussian elimination", "language": "Ruby", "task": "Solve '''Ax=b''' using Gaussian elimination then backwards substitution. \n\n'''A''' being an '''n''' by '''n''' matrix. \n\nAlso, '''x''' and '''b''' are '''n''' by '''1''' vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* the Wikipedia entry: Gaussian elimination\n\n", "solution": "require 'bigdecimal/ludcmp'\ninclude LUSolve\n\nBigDecimal::limit(30)\n\na = [1.00, 0.00, 0.00, 0.00, 0.00, 0.00,\n 1.00, 0.63, 0.39, 0.25, 0.16, 0.10,\n 1.00, 1.26, 1.58, 1.98, 2.49, 3.13,\n 1.00, 1.88, 3.55, 6.70, 12.62, 23.80,\n 1.00, 2.51, 6.32, 15.88, 39.90, 100.28,\n 1.00, 3.14, 9.87, 31.01, 97.41, 306.02].map{|i|BigDecimal(i,16)}\nb = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02].map{|i|BigDecimal(i,16)}\n\nn = 6\nzero = BigDecimal(\"0.0\")\none = BigDecimal(\"1.0\")\n\nlusolve(a, b, ludecomp(a, n, zero,one), zero).each{|v| puts v.to_s('F')[0..20]}"} {"title": "Generate Chess960 starting position", "language": "Ruby", "task": "Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:\n\n* as in the standard chess game, all eight white pawns must be placed on the second rank.\n* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:\n** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)\n** the King must be between two rooks (with any number of other pieces between them all)\n* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)\n\n\nWith those constraints there are '''960''' possible starting positions, thus the name of the variant.\n\n\n;Task:\nThe purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "pieces = %i(\u2654 \u2655 \u2658 \u2658 \u2657 \u2657 \u2656 \u2656)\nregexes = [/\u2657(..)*\u2657/, /\u2656.*\u2654.*\u2656/]\nrow = pieces.shuffle.join until regexes.all?{|re| re.match(row)} \nputs row"} {"title": "Generate random chess position", "language": "Ruby", "task": "Generate a random chess position in FEN format. \n\nThe position does not have to be realistic or even balanced, but it must comply to the following rules:\n:* there is one and only one king of each color (one black king and one white king);\n:* the kings must not be placed on adjacent squares;\n:* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);\n:* including the kings, up to 32 pieces of either color can be placed. \n:* There is no requirement for material balance between sides. \n:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. \n:* it is white's turn.\n:* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1).\n\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.\n\n", "solution": "def hasNK( board, a, b )\n for g in -1 .. 1\n for f in -1 .. 1\n aa = a + f; bb = b + g\n if aa.between?( 0, 7 ) && bb.between?( 0, 7 )\n p = board[aa + 8 * bb]\n if p == \"K\" || p == \"k\"; return true; end\n end \n end\n end\n return false\nend\ndef generateBoard( board, pieces )\n while( pieces.length > 1 )\n p = pieces[pieces.length - 1]\n pieces = pieces[0...-1]\n while( true )\n a = rand( 8 ); b = rand( 8 )\n if ( ( b == 0 || b == 7 ) && ( p == \"P\" || p == \"p\" ) ) || \n ( ( p == \"k\" || p == \"K\" ) && hasNK( board, a, b ) ); next; end \n if board[a + b * 8] == nil; break;end\n end\n board[a + b * 8] = p\n end\nend\npieces = \"ppppppppkqrrbbnnPPPPPPPPKQRRBBNN\"\nfor i in 0 .. 10\n e = pieces.length - 1\n while e > 0\n p = rand( e ); t = pieces[e]; \n pieces[e] = pieces[p]; pieces[p] = t; e -= 1\n end\nend\nboard = Array.new( 64 ); generateBoard( board, pieces )\nputs\ne = 0\nfor j in 0 .. 7 \n for i in 0 .. 7 \n if board[i + 8 * j] == nil; e += 1\n else \n if e > 0; print( e ); e = 0; end\n print( board[i + 8 * j] )\n end\n end\n if e > 0; print( e ); e = 0; end\n if j < 7; print( \"/\" ); end\nend\nprint( \" w - - 0 1\\n\" )\nfor j in 0 .. 7 \n for i in 0 .. 7 \n if board[i + j * 8] == nil; print( \".\" )\n else print( board[i + j * 8] ); end\n end\n puts\nend\n"} {"title": "Generator/Exponential", "language": "Ruby", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "# This solution cheats and uses only one generator!\n\ndef powers(m)\n return enum_for(__method__, m) unless block_given?\n 0.step{|n| yield n**m}\nend\n\ndef squares_without_cubes\n return enum_for(__method__) unless block_given?\n \n cubes = powers(3)\n c = cubes.next\n powers(2) do |s|\n c = cubes.next while c < s\n yield s unless c == s\n end\nend\n\np squares_without_cubes.take(30).drop(20)\n# p squares_without_cubes.lazy.drop(20).first(10) # Ruby 2.0+"} {"title": "Generator/Exponential", "language": "Ruby from Python", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "def filtered(s1, s2)\n return enum_for(__method__, s1, s2) unless block_given?\n v, f = s1.next, s2.next\n loop do\n v > f and f = s2.next and next\n v < f and yield v\n v = s1.next\n end\nend\n\nsquares, cubes = powers(2), powers(3)\nf = filtered(squares, cubes)\np f.take(30).last(10)\n# p f.lazy.drop(20).first(10) # Ruby 2.0+"} {"title": "Giuga numbers", "language": "Ruby", "task": "Definition\nA '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors\n'''f''' divide (n/f - 1) exactly.\n\nAll known Giuga numbers are even though it is not known for certain that there are no odd examples. \n\n;Example\n30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:\n* 30/2 - 1 = 14 is divisible by 2\n* 30/3 - 1 = 9 is divisible by 3\n* 30/5 - 1 = 5 is divisible by 5\n\n;Task\nDetermine and show here the first four Giuga numbers.\n\n;Stretch\nDetermine the fifth Giuga number and any more you have the patience for.\n\n;References\n\n* Wikipedia: Giuga number\n* OEIS:A007850 - Giuga numbers\n\n", "solution": "require 'prime'\n\ngiuga = (1..).lazy.select do |n| \n pd = n.prime_division\n pd.sum{|_, d| d} > 1 && #composite\n pd.all?{|f, _| (n/f - 1) % f == 0} \nend\n\np giuga.take(4).to_a\n"} {"title": "Globally replace text in several files", "language": "Ruby", "task": "Replace every occurring instance of a piece of text in a group of text files with another one. \n\n\nFor this task we want to replace the text \"'''Goodbye London!'''\" with \"'''Hello New York!'''\" for a list of files.\n\n", "solution": "Like Perl:\n\nruby -pi -e \"gsub('Goodbye London!', 'Hello New York!')\" a.txt b.txt c.txt\n\n\n"} {"title": "Gray code", "language": "Ruby", "task": "Karnaugh maps in order from left to right or top to bottom.\nCreate functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* Converting Between Gray and Binary Codes. It includes step-by-step animations.\n\n", "solution": "class Integer\n # Converts a normal integer to a Gray code.\n def to_gray\n raise Math::DomainError, \"integer is negative\" if self < 0\n self ^ (self >> 1)\n end\n \n # Converts a Gray code to a normal integer.\n def from_gray\n raise Math::DomainError, \"integer is negative\" if self < 0\n recurse = proc do |i|\n next 0 if i == 0\n o = recurse[i >> 1] << 1\n o | (i[0] ^ o[1])\n end\n recurse[self]\n end\nend\n\n(0..31).each do |number|\n encoded = number.to_gray\n decoded = encoded.from_gray\n printf \"%2d : %5b => %5b => %5b : %2d\\n\",\n number, number, encoded, decoded, decoded\nend"} {"title": "Greatest subsequential sum", "language": "Ruby", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "[ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5],\n [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],\n [-1, -2, -3, -4, -5],\n []\n].each do |input|\n puts \"\\nInput seq: #{input}\"\n puts \" Max sum: %d\\n Subseq: %s\" % subarray_sum(input)\nend"} {"title": "Greedy algorithm for Egyptian fractions", "language": "Ruby from Python", "task": "An Egyptian fraction is the sum of distinct unit fractions such as: \n\n:::: \\tfrac{1}{2} + \\tfrac{1}{3} + \\tfrac{1}{16} \\,(= \\tfrac{43}{48}) \n\nEach fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). \n\nFibonacci's Greedy algorithm for Egyptian fractions expands the fraction \\tfrac{x}{y} to be represented by repeatedly performing the replacement\n\n:::: \\frac{x}{y} = \\frac{1}{\\lceil y/x\\rceil} + \\frac{(-y)\\!\\!\\!\\!\\mod x}{y\\lceil y/x\\rceil} \n\n\n(simplifying the 2nd term in this replacement as necessary, and where \\lceil x \\rceil is the ''ceiling'' function).\n\n\n\nFor this task, Proper and improper fractions must be able to be expressed.\n\n\nProper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that a < b, and \n\nimproper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. \n\n\n(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)\n\nFor improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n''].\n\n\n;Task requirements:\n* show the Egyptian fractions for: \\tfrac{43}{48} and \\tfrac{5}{121} and \\tfrac{2014}{59} \n* for all proper fractions, \\tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:\n::* the largest number of terms,\n::* the largest denominator.\n* for all one-, two-, and three-digit integers, find and show (as above). {extra credit}\n\n\n;Also see:\n* Wolfram MathWorld(tm) entry: Egyptian fraction\n\n", "solution": "def ef(fr)\n ans = []\n if fr >= 1\n return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1\n intfr = fr.to_i\n ans, fr = [intfr], fr - intfr\n end\n x, y = fr.numerator, fr.denominator\n while x != 1\n ans << Rational(1, (1/fr).ceil)\n fr = Rational(-y % x, y * (1/fr).ceil)\n x, y = fr.numerator, fr.denominator\n end\n ans << fr\nend\n\nfor fr in [Rational(43, 48), Rational(5, 121), Rational(2014, 59)]\n puts '%s => %s' % [fr, ef(fr).join(' + ')]\nend\n\nlenmax = denommax = [0]\nfor b in 2..99\n for a in 1...b\n fr = Rational(a,b)\n e = ef(fr)\n elen, edenom = e.length, e[-1].denominator\n lenmax = [elen, fr] if elen > lenmax[0]\n denommax = [edenom, fr] if edenom > denommax[0]\n end\nend\nputs 'Term max is %s with %i terms' % [lenmax[1], lenmax[0]]\ndstr = denommax[0].to_s\nputs 'Denominator max is %s with %i digits' % [denommax[1], dstr.size], dstr"} {"title": "Hailstone sequence", "language": "Ruby", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "This program uses new methods (Integer#even? and Enumerable#max_by) from Ruby 1.8.7.\n"} {"title": "Hailstone sequence", "language": "Ruby 1.8.7", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "module Hailstone\n ListNode = Struct.new(:value, :size, :succ) do\n def each\n node = self\n while node\n yield node.value\n node = node.succ\n end\n end\n end\n \n @@sequence = {1 => ListNode[1,1]}\n \n module_function\n \n def sequence(n)\n unless @@sequence[n]\n m, ary = n, []\n until succ = @@sequence[m]\n ary << m\n m = m.even? ? (m / 2) : (3 * m + 1)\n end\n ary.reverse_each do |m|\n @@sequence[m] = succ = ListNode[m, succ.size + 1, succ]\n end\n end\n @@sequence[n]\n end\nend\n\nputs \"for n = 27, show sequence length and first and last 4 elements\"\nhs27 = Hailstone.sequence(27).entries\np [hs27.size, hs27[0..3], hs27[-4..-1]]\n\n# find the longest sequence among n less than 100,000\nn = (1 ... 100_000).max_by{|n| Hailstone.sequence(n).size}\nputs \"#{n} has a hailstone sequence length of #{Hailstone.sequence(n).size}\"\nputs \"the largest number in that sequence is #{Hailstone.sequence(n).max}\""} {"title": "Harmonic series", "language": "Ruby", "task": "{{Wikipedia|Harmonic number}}\n\n\nIn mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers: \n\n\n'''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n'''\n\nThe series of harmonic numbers thus obtained is often loosely referred to as the harmonic series. \n\nHarmonic numbers are closely related to the Euler-Mascheroni constant.\n\nThe harmonic series is divergent, albeit quite slowly, and grows toward infinity.\n\n\n;Task\n* Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers.\n* Use that procedure to show the values of the first 20 harmonic numbers.\n* Find and show the position in the series of the first value greater than the integers 1 through 5\n\n\n;Stretch\n* Find and show the position in the series of the first value greater than the integers 6 through 10\n\n\n;Related\n* [[Egyptian fractions]]\n\n\n", "solution": "harmonics = Enumerator.new do |y|\n res = 0\n (1..).each {|n| y << res += Rational(1, n) }\nend\n\nn = 20\nThe first #{n} harmonics (as rationals):\"\"\nharmonics.take(n).each_slice(5){|slice| puts \"%20s\"*slice.size % slice }\n\nputs\nmilestones = (1..10).to_a\nharmonics.each.with_index(1) do |h,i|\n if h > milestones.first then\n puts \"The first harmonic number > #{milestones.shift} is #{h.to_f} at position #{i}\"\n end\n break if milestones.empty?\nend\n"} {"title": "Harshad or Niven series", "language": "Ruby 2.4", "task": "The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. \n\nFor example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.\n\nAssume that the series is defined as the numbers in increasing order.\n\n\n;Task:\nThe task is to create a function/method/procedure to generate successive members of the Harshad sequence. \n\nUse it to:\n::* list the first '''20''' members of the sequence, and\n::* list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* Increasing gaps between consecutive Niven numbers\n\n\n;See also\n* OEIS: A005349\n\n", "solution": "harshad = 1.step.lazy.select { |n| n % n.digits.sum == 0 }\n\nputs \"The first 20 harshard numbers are: \\n#{ harshad.first(20) }\"\nputs \"The first harshard number > 1000 is #{ harshad.find { |n| n > 1000 } }\"\n"} {"title": "Hash join", "language": "Ruby", "task": "{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "def hashJoin(table1, index1, table2, index2)\n # hash phase\n h = table1.group_by {|s| s[index1]}\n h.default = []\n # join phase\n table2.collect {|r|\n h[r[index2]].collect {|s| [s, r]}\n }.flatten(1)\nend\n\ntable1 = [[27, \"Jonah\"],\n [18, \"Alan\"],\n [28, \"Glory\"],\n [18, \"Popeye\"],\n [28, \"Alan\"]]\ntable2 = [[\"Jonah\", \"Whales\"],\n [\"Jonah\", \"Spiders\"],\n [\"Alan\", \"Ghosts\"],\n [\"Alan\", \"Zombies\"],\n [\"Glory\", \"Buffy\"]]\n\nhashJoin(table1, 1, table2, 0).each { |row| p row }"} {"title": "Haversine formula", "language": "Ruby", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "include Math\n\nRadius = 6372.8 # rough radius of the Earth, in kilometers\n\ndef spherical_distance(start_coords, end_coords)\n lat1, long1 = deg2rad *start_coords\n lat2, long2 = deg2rad *end_coords\n 2 * Radius * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2))\nend\n\ndef deg2rad(lat, long)\n [lat * PI / 180, long * PI / 180]\nend\n\nbna = [36.12, -86.67]\nlax = [33.94, -118.4]\n\nputs \"%.1f\" % spherical_distance(bna, lax)"} {"title": "Haversine formula", "language": "Ruby from Python", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "include Math\n \ndef haversine(lat1, lon1, lat2, lon2)\n r = 6372.8 # Earth radius in kilometers\n deg2rad = PI/180 # convert degress to radians\n \n dLat = (lat2 - lat1) * deg2rad\n dLon = (lon2 - lon1) * deg2rad\n lat1 = lat1 * deg2rad\n lat2 = lat2 * deg2rad\n \n a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2\n c = 2 * asin(sqrt(a))\n r * c\nend\n\nputs \"distance is #{haversine(36.12, -86.67, 33.94, -118.40)} km \"\n"} {"title": "Here document", "language": "Ruby", "task": "A ''here document'' (or \"heredoc\") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. \n\nDepending on the language being used, a ''here document'' is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string. \n\nThe 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.\n\n\n;Task:\nDemonstrate the use of ''here documents'' within the language.\n\n;Related task:\n* [[Documentation]]\n\n", "solution": "address = < long\n end\n \n attr_reader :sides, :perimeter, :area\n \n def initialize(a,b,c)\n @sides = [a, b, c].sort\n @perimeter = a + b + c\n s = @perimeter / 2.0\n @area = Math.sqrt(s * (s - a) * (s - b) * (s - c))\n end\n \n def heronian?\n area == area.to_i\n end\n \n def <=>(other)\n [area, perimeter, sides] <=> [other.area, other.perimeter, other.sides]\n end\n \n def to_s\n \"%-11s%6d%8.1f\" % [sides.join('x'), perimeter, area]\n end\nend\n\nmax, area = 200, 210\nprim_triangles = []\n1.upto(max) do |a|\n a.upto(max) do |b|\n b.upto(max) do |c|\n next if a.gcd(b).gcd(c) > 1\n prim_triangles << Triangle.new(a, b, c) if Triangle.valid?(a, b, c)\n end\n end\nend\n\nsorted = prim_triangles.select(&:heronian?).sort\n\nputs \"Primitive heronian triangles with sides upto #{max}: #{sorted.size}\"\nputs \"\\nsides perim. area\"\nputs sorted.first(10).map(&:to_s)\nputs \"\\nTriangles with an area of: #{area}\"\nsorted.each{|tr| puts tr if tr.area == area}"} {"title": "Hex words", "language": "Ruby", "task": "Definition\nFor 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'''.\n\n;Task\nUsing unixdict.txt, find all hex words with '''4''' letters or more.\n\nConvert each such word to its decimal equivalent and compute its base 10 digital root.\n\nDisplay all three in increasing order of digital root and show the total count of such words.\n\nKeeping 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.\n\n", "solution": "def report(a)\n puts\n a.each {|hexword| puts \"%6s %8d %d\" % hexword}\n puts \"Total count of these words: #{a.size}\"\nend\n\nhexwords = File.readlines(\"unixdict.txt\", chomp: true).reject{|w| w.size < 4 || w.match?(/[^abcdef]/) }\nres = hexwords.map{|hw| [hw, hw.to_i(16), 1 + (hw.to_i(16) - 1) % 9]}.sort_by(&:last)\nreport( res )\nreport( res.reject{|hw| hw[0].chars.uniq.size < 4}.sort_by{|w| -w[1]} )\n"} {"title": "Hickerson series of almost integers", "language": "Ruby", "task": "The following function, due to D. Hickerson, is said to generate \"Almost integers\" by the \n\"Almost Integer\" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.)\n\n\nThe function is: h(n) = {\\operatorname{n}!\\over2(\\ln{2})^{n+1}}\n\n\nIt is said to produce \"almost integers\" for '''n''' between '''1''' and '''17'''. \nThe purpose of the task is to verify this assertion.\n\nAssume that an \"almost integer\" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation\n\n\n;Task:\nCalculate all values of the function checking and stating which are \"almost integers\".\n\nNote: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:\n h(18) = 3385534663256845326.39...\n\n", "solution": "require \"bigdecimal\"\n\nLN2 = BigMath::log(2,16) #Use LN2 = Math::log(2) to see the difference with floats\nFACTORIALS = Hash.new{|h,k| h[k] = k * h[k-1]}\nFACTORIALS[0] = 1\n\ndef hickerson(n)\n FACTORIALS[n] / (2 * LN2 ** (n+1))\nend\n\ndef nearly_int?(n)\n int = n.round\n n.between?(int - 0.1, int + 0.1)\nend\n\n1.upto(17) do |n|\n h = hickerson(n)\n str = nearly_int?(h) ? \"nearly integer\" : \"NOT nearly integer\"\n 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\nend"} {"title": "History variables", "language": "Ruby", "task": "''Storing the history of objects in a program is a common task. \nMaintaining 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.''\n\n''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.\n'' \n\n\"History Variables: \nThe Semantics, Formal Correctness, and Implementation of History Variables \nin an Imperative Programming Language\" by Mallon and Takaoka\n\nConcept also discussed on LtU and Patents.com.\n\n;Task: \nDemonstrate History variable support: \n* enable history variable support (if needed) \n* define a history variable\n* assign three values\n* non-destructively display the history\n* recall the three values. \n\nFor extra points, if the language of choice does not support history variables, \ndemonstrate how this might be implemented.\n\n", "solution": "foo_hist = []\ntrace_var(:$foo){|v| foo_hist.unshift(v)}\n\n$foo = \"apple\"\n$foo = \"pear\"\n$foo = \"banana\"\n\np foo_hist # => [\"banana\", \"pear\", \"apple\"]\n"} {"title": "Hofstadter-Conway $10,000 sequence", "language": "Ruby", "task": "The definition of the sequence is colloquially described as:\n* Starting with the list [1,1],\n* Take the last number in the list so far: 1, I'll call it x.\n* Count forward x places from the beginning of the list to find the first number to add (1)\n* Count backward x places from the end of the list to find the second number to add (1)\n* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* This would then produce [1,1,2] where 2 is the third element of the sequence.\n\nNote that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.\n\nA less wordy description of the sequence is:\n a(1)=a(2)=1\n a(n)=a(a(n-1))+a(n-a(n-1))\n\nThe sequence begins:\n 1, 1, 2, 2, 3, 4, 4, 4, 5, ...\n\nInteresting features of the sequence are that:\n* a(n)/n tends to 0.5 as n grows towards infinity.\n* a(n)/n where n is a power of 2 is 0.5\n* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.\n\na(n) / n for n in 1..256 \n\n\nThe sequence is so named because John Conway offered a prize of $10,000 to the first person who could\nfind the first position, p in the sequence where \n |a(n)/n| < 0.55 for all n > p\nIt was later found that Hofstadter had also done prior work on the sequence.\n\nThe '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).\n\n\n;Task:\n# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20\n# 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\n\n\n\n;Also see:\n* Conways Challenge Sequence, Mallows' own account.\n* Mathworld Article.\n\n", "solution": "class HofstadterConway10000\n def initialize\n @sequence = [nil, 1, 1]\n end\n \n def [](n)\n raise ArgumentError, \"n must be >= 1\" if n < 1\n a = @sequence\n a.length.upto(n) {|i| a[i] = a[a[i-1]] + a[i-a[i-1]] }\n a[n]\n end\nend\n\nhc = HofstadterConway10000.new\n\nmallows = nil\n(1...20).each do |i|\n j = i + 1\n max_n, max_v = -1, -1\n (2**i .. 2**j).each do |n|\n v = hc[n].to_f / n\n max_n, max_v = n, v if v > max_v\n # Mallows number\n mallows = n if v >= 0.55\n end\n puts \"maximum between 2^%2d and 2^%2d occurs at%7d: %.8f\" % [i, j, max_n, max_v]\nend\n\nputs \"the mallows number is #{mallows}\""} {"title": "Hofstadter Figure-Figure sequences", "language": "Ruby from Tcl", "task": "These two sequences of positive integers are defined as:\n:::: \\begin{align}\nR(1)&=1\\ ;\\ S(1)=2 \\\\\nR(n)&=R(n-1)+S(n-1), \\quad n>1.\n\\end{align}\n\nThe sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).\n\nSequence R starts: \n 1, 3, 7, 12, 18, ...\nSequence S starts: \n 2, 4, 5, 6, 8, ...\n\n\n;Task:\n# 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).\n# No maximum value for '''n''' should be assumed.\n# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69\n# 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.\n\n\n;References:\n* Sloane's A005228 and A030124.\n* Wolfram MathWorld\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "$r = [nil, 1]\n$s = [nil, 2]\n\ndef buildSeq(n)\n current = [ $r[-1], $s[-1] ].max\n while $r.length <= n || $s.length <= n\n idx = [ $r.length, $s.length ].min - 1\n current += 1\n if current == $r[idx] + $s[idx]\n $r << current\n else\n $s << current\n end\n end\nend\n\ndef ffr(n)\n buildSeq(n)\n $r[n]\nend\n\ndef ffs(n)\n buildSeq(n)\n $s[n]\nend\n\nrequire 'set'\nrequire 'test/unit'\n\nclass TestHofstadterFigureFigure < Test::Unit::TestCase\n def test_first_ten_R_values\n r10 = 1.upto(10).map {|n| ffr(n)}\n assert_equal(r10, [1, 3, 7, 12, 18, 26, 35, 45, 56, 69])\n end\n\n def test_40_R_and_960_S_are_1_to_1000\n rs_values = Set.new\n rs_values.merge( 1.upto(40).collect {|n| ffr(n)} )\n rs_values.merge( 1.upto(960).collect {|n| ffs(n)} )\n assert_equal(rs_values, Set.new( 1..1000 ))\n end\nend"} {"title": "Hofstadter Figure-Figure sequences", "language": "Ruby from Python", "task": "These two sequences of positive integers are defined as:\n:::: \\begin{align}\nR(1)&=1\\ ;\\ S(1)=2 \\\\\nR(n)&=R(n-1)+S(n-1), \\quad n>1.\n\\end{align}\n\nThe sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).\n\nSequence R starts: \n 1, 3, 7, 12, 18, ...\nSequence S starts: \n 2, 4, 5, 6, 8, ...\n\n\n;Task:\n# 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).\n# No maximum value for '''n''' should be assumed.\n# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69\n# 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.\n\n\n;References:\n* Sloane's A005228 and A030124.\n* Wolfram MathWorld\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "R = Enumerator.new do |y|\n y << n = 1\n S.each{|s_val| y << n += s_val}\nend\n\nS = Enumerator.new do |y|\n y << 2\n y << 4\n u = 5\n R.each do |r_val|\n next if u > r_val\n (u...r_val).each{|r| y << r}\n u = r_val+1\n end\nend\n\np R.take(10)\np S.take(10)\np (R.take(40)+ S.take(960)).sort == (1..1000).to_a\n"} {"title": "Hofstadter Q sequence", "language": "Ruby", "task": "The Hofstadter Q sequence is defined as:\n:: \\begin{align}\nQ(1)&=Q(2)=1, \\\\\nQ(n)&=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)\\big), \\quad n>2.\n\\end{align}\n\n\nIt 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.\n\n\n;Task:\n* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 \n* Confirm and display that the 1000th term is: 502\n\n\n;Optional extra credit\n* 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.\n* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.\n(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).\n\n", "solution": "@cache = []\ndef Q(n)\n if @cache[n].nil?\n case n\n when 1, 2 then @cache[n] = 1\n else @cache[n] = Q(n - Q(n-1)) + Q(n - Q(n-2))\n end\n end\n @cache[n]\nend\n\nputs \"first 10 numbers in the sequence: #{(1..10).map {|n| Q(n)}}\"\nputs \"1000'th term: #{Q(1000)}\" \n\nprev = Q(1)\ncount = 0\n2.upto(100_000) do |n| \n q = Q(n)\n count += 1 if q < prev \n prev = q\nend\nputs \"number of times in the first 100,000 terms where Q(i) 128"} {"title": "ISBN13 check digit", "language": "Ruby", "task": "Validate the check digit of an ISBN-13 code:\n::* Multiply every other digit by '''3'''.\n::* Add these numbers and the other digits.\n::* Take the remainder of this number after division by '''10'''.\n::* If it is '''0''', the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* 978-0596528126 (good)\n::::* 978-0596528120 (bad)\n::::* 978-1788399081 (good)\n::::* 978-1788399083 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* for details: 13-digit ISBN method of validation. (installs cookies.)\n\n", "solution": "def validISBN13?(str)\n cleaned = str.delete(\"^0-9\").chars\n return false unless cleaned.size == 13\n cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0\nend\n\nisbns = [\"978-1734314502\", \"978-1734314509\", \"978-1788399081\", \"978-1788399083\"]\nisbns.each{|isbn| puts \"#{isbn}: #{validISBN13?(isbn)}\" }\n"} {"title": "I before E except after C", "language": "Ruby", "task": "The phrase \"I before E, except after C\" is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# ''\"I before E when not preceded by C\"''\n:::# ''\"E before I when preceded by C\"''\n\n\nIf both sub-phrases are plausible then the original phrase can be said to be plausible.\n\nSomething 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).\n \n\n;Stretch goal:\nAs 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.\n\n\n''Show your output here as well as your program.''\n\n\n\n\n;cf.:\n* Schools to rethink 'i before e' - BBC news, 20 June 2009\n* I Before E Except After C - QI Series 8 Ep 14, (humorous)\n* Companion website for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "require 'open-uri'\n\nplausibility_ratio = 2\ncounter = Hash.new(0)\npath = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'\nrules = [['I before E when not preceded by C:', 'ie', 'ei'],\n ['E before I when preceded by C:', 'cei', 'cie']]\n\nopen(path){|f| f.each{|line| line.scan(/ie|ei|cie|cei/){|match| counter[match] += 1 }}}\n\noverall_plausible = rules.all? do |(str, x, y)|\n num_x, num_y, ratio = counter[x], counter[y], counter[x] / counter[y].to_f\n plausibility = ratio > plausibility_ratio\n puts str\n puts \"#{x}: #{num_x}; #{y}: #{num_y}; Ratio: #{ratio.round(2)}: #{ plausibility ? 'Plausible' : 'Implausible'}\"\n plausibility\nend\n\nputs \"Overall: #{overall_plausible ? 'Plausible' : 'Implausible'}.\"\n"} {"title": "Identity matrix", "language": "Ruby", "task": "Build an identity matrix of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', \nwhere the diagonal elements are all '''1'''s (ones), \nand all the other elements are all '''0'''s (zeroes).\n\n\nI_n = \\begin{bmatrix}\n 1 & 0 & 0 & \\cdots & 0 \\\\\n 0 & 1 & 0 & \\cdots & 0 \\\\\n 0 & 0 & 1 & \\cdots & 0 \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\cdots & 1 \\\\\n\\end{bmatrix}\n\n\n;Related tasks:\n* [[Spiral matrix]]\n* [[Zig-zag matrix]] \n* [[Ulam_spiral_(for_primes)]]\n\n", "solution": "def identity(size)\n Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}}\nend\n\n[4,5,6].each do |size|\n puts size, identity(size).map {|r| r.to_s}, \"\"\nend"} {"title": "Idiomatically determine all the lowercase and uppercase letters", "language": "Ruby", "task": "Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.\nThe method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n \n\n;Task requirements\n\nDisplay the set of all:\n::::::* lowercase letters \n::::::* uppercase letters\n\nthat can be used (allowed) by the computer program,\n\nwhere ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. \n\n\nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\n\n;See also\n* Idiomatically determine all the characters that can be used for symbols.\n\n", "solution": "puts \"Lowercase:\", [*\"a\"..\"z\"].join, \"Uppercase:\", [*\"A\"..\"Z\"].join"} {"title": "Imaginary base numbers", "language": "Ruby 2.3", "task": "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. \n\n''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]''\n\nOther imaginary bases are possible too but are not as widely discussed and aren't specifically named.\n\n'''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. \n\nAt a minimum, support quater-imaginary (base 2i).\n\nFor extra kudos, support positive or negative bases 2i through 6i (or higher).\n\nAs a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.\n\nSee Wikipedia: Quater-imaginary_base for more details. \n\nFor reference, here are some some decimal and complex numbers converted to quater-imaginary.\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1\n 1\n\n\n2\n 2\n\n\n3\n 3\n\n\n4\n 10300\n\n\n5\n 10301\n\n\n6\n 10302\n\n\n7\n 10303\n\n\n8\n 10200\n\n\n9\n 10201\n\n\n10\n 10202\n\n\n11\n 10203\n\n\n12\n 10100\n\n\n13\n 10101\n\n\n14\n 10102\n\n\n15\n 10103\n\n\n16\n 10000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1\n 103\n\n\n-2\n 102\n\n\n-3\n 101\n\n\n-4\n 100\n\n\n-5\n 203\n\n\n-6\n 202\n\n\n-7\n 201\n\n\n-8\n 200\n\n\n-9\n 303\n\n\n-10\n 302\n\n\n-11\n 301\n\n\n-12\n 300\n\n\n-13\n 1030003\n\n\n-14\n 1030002\n\n\n-15\n 1030001\n\n\n-16\n 1030000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1i\n10.2\n\n\n2i\n10.0\n\n\n3i\n20.2\n\n\n4i\n20.0\n\n\n5i\n30.2\n\n\n6i\n30.0\n\n\n7i\n103000.2\n\n\n8i\n103000.0\n\n\n9i\n103010.2\n\n\n10i\n103010.0\n\n\n11i\n103020.2\n\n\n12i\n103020.0\n\n\n13i\n103030.2\n\n\n14i\n103030.0\n\n\n15i\n102000.2\n\n\n16i\n102000.0\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1i\n0.2\n\n\n-2i\n1030.0\n\n\n-3i\n1030.2\n\n\n-4i\n1020.0\n\n\n-5i\n1020.2\n\n\n-6i\n1010.0\n\n\n-7i\n1010.2\n\n\n-8i\n1000.0\n\n\n-9i\n1000.2\n\n\n-10i\n2030.0\n\n\n-11i\n2030.2\n\n\n-12i\n2020.0\n\n\n-13i\n2020.2\n\n\n-14i\n2010.0\n\n\n-15i\n2010.2\n\n\n-16i\n2000.0\n\n\n\n\n\n", "solution": "# Extend class Integer with a string conveter.\n\nclass Integer\n def as_str()\n return to_s()\n end\nend\n\n# Extend class Complex with a string conveter (works only with Gaussian integers).\n\nclass Complex\n def as_str()\n return '0' if self == 0\n return real.to_i.to_s if imag == 0\n return imag.to_i.to_s + 'i' if real == 0\n return real.to_i.to_s + '+' + imag.to_i.to_s + 'i' if imag >= 0\n return real.to_i.to_s + '-' + (-(imag.to_i)).to_s + 'i'\n end\nend\n\n# Emit various tables of conversions.\n\n1.step(16) do |gi|\n puts(\" %4s -> %8s -> %4s %4s -> %8s -> %4s\" %\n [gi.as_str, base2i_encode(gi), base2i_decode(base2i_encode(gi)).as_str,\n (-gi).as_str, base2i_encode(-gi), base2i_decode(base2i_encode(-gi)).as_str])\nend\nputs\n1.step(16) do |gi|\n gi *= 0+1i\n puts(\" %4s -> %8s -> %4s %4s -> %8s -> %4s\" %\n [gi.as_str, base2i_encode(gi), base2i_decode(base2i_encode(gi)).as_str,\n (-gi).as_str, base2i_encode(-gi), base2i_decode(base2i_encode(-gi)).as_str])\nend\nputs\n0.step(3) do |m|\n 0.step(3) do |l|\n 0.step(3) do |h|\n qi = (100 * h + 10 * m + l).to_s\n gi = base2i_decode(qi)\n md = base2i_encode(gi).match(/^(?[0-3]+)(?:\\.0)?$/)\n print(\" %4s -> %6s -> %4s\" % [qi, gi.as_str, md[:num]])\n end\n puts\n end\nend"} {"title": "Increasing gaps between consecutive Niven numbers", "language": "Ruby", "task": "Note: '''Niven''' numbers are also called '''Harshad''' numbers.\n:::: They are also called '''multidigital''' numbers.\n\n\n'''Niven''' numbers are positive integers which are evenly divisible by the sum of its\ndigits (expressed in base ten).\n\n''Evenly divisible'' means ''divisible with no remainder''.\n\n\n;Task:\n:* find the gap (difference) of a Niven number from the previous Niven number\n:* if the gap is ''larger'' than the (highest) previous gap, then:\n:::* show the index (occurrence) of the gap (the 1st gap is '''1''')\n:::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''')\n:::* show the Niven number that starts the gap\n:::* show all numbers with comma separators where appropriate (optional)\n:::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864'''\n:* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number\n:* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer\n:* show all output here, on this page\n\n\n;Related task:\n:* Harshad or Niven series.\n\n\n;Also see:\n:* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers.\n:* (PDF) version of the (above) article by Doyon.\n\n", "solution": "nivens = Enumerator.new {|y| (1..).each {|n| y << n if n.remainder(n.digits.sum).zero?} }\n\ncur_gap = 0\nputs 'Gap Index of gap Starting Niven'\n\nnivens.each_cons(2).with_index(1) do |(n1, n2), i|\n break if i > 10_000_000\n if n2-n1 > cur_gap then\n printf \"%3d %15s %15s\\n\", n2-n1, i, n1\n cur_gap = n2-n1\n end\nend\n"} {"title": "Index finite lists of positive integers", "language": "Ruby from Python", "task": "It is known that the set of finite lists of positive integers is countable. \n\nThis means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. \n\n\n;Task:\nImplement such a mapping:\n:* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers.\n:* write a function ''unrank'' which is the ''rank'' inverse function.\n\n\nDemonstrate your solution by:\n:* picking a random-length list of random positive integers\n:* turn it into an integer, and \n:* get the list back.\n\n\nThere are many ways to do this. Feel free to choose any one you like.\n\n\n;Extra credit:\nMake the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.\n\n", "solution": "def unrank(n)\n return [0] if n==1\n n.to_s(2)[1..-1].split('0',-1).map(&:size)\nend\n\ndef rank(x)\n return 0 if x.empty?\n ('1' + x.map{ |a| '1'*a }.join('0')).to_i(2)\nend\n\nfor x in 0..10\n puts \"%3d : %-18s: %d\" % [x, a=unrank(x), rank(a)]\nend\n\nputs\nx = [1, 2, 3, 5, 8]\nputs \"#{x} => #{rank(x)} => #{unrank(rank(x))}\""} {"title": "Integer overflow", "language": "Ruby", "task": "Some languages support one or more integer types of the underlying processor.\n\nThis integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.\nThe integers supported by such a type can be ''signed'' or ''unsigned''.\n\nArithmetic for machine level integers can often be done by single CPU instructions.\nThis allows high performance and is the main reason to support machine level integers.\n\n\n;Definition:\nAn integer overflow happens when the result of a computation does not fit into the fixed size integer.\nThe result can be too small or too big to be representable in the fixed size integer.\n\n\n;Task:\nWhen a language has fixed size integer types, create a program that\ndoes arithmetic computations for the fixed size integers of the language.\n\nThese computations must be done such that the result would overflow.\n\nThe program should demonstrate what the following expressions do.\n\n\nFor 32-bit signed integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit signed integer\n|-\n| -(-2147483647-1)\n| 2147483648\n|-\n| 2000000000 + 2000000000\n| 4000000000\n|-\n| -2147483647 - 2147483647\n| -4294967294\n|-\n| 46341 * 46341\n| 2147488281\n|-\n| (-2147483647-1) / -1\n| 2147483648\n|}\n\nFor 64-bit signed integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit signed integer\n|-\n| -(-9223372036854775807-1)\n| 9223372036854775808\n|-\n| 5000000000000000000+5000000000000000000\n| 10000000000000000000\n|-\n| -9223372036854775807 - 9223372036854775807\n| -18446744073709551614\n|-\n| 3037000500 * 3037000500\n| 9223372037000250000\n|-\n| (-9223372036854775807-1) / -1\n| 9223372036854775808\n|}\n\nFor 32-bit unsigned integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit unsigned integer\n|-\n| -4294967295\n| -4294967295\n|-\n| 3000000000 + 3000000000\n| 6000000000\n|-\n| 2147483647 - 4294967295\n| -2147483648\n|-\n| 65537 * 65537\n| 4295098369\n|}\n\nFor 64-bit unsigned integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit unsigned integer\n|-\n| -18446744073709551615\n| -18446744073709551615\n|-\n| 10000000000000000000 + 10000000000000000000\n| 20000000000000000000\n|-\n| 9223372036854775807 - 18446744073709551615\n| -9223372036854775808\n|-\n| 4294967296 * 4294967296\n| 18446744073709551616\n|}\n\n\n;Notes:\n:* When the integer overflow does trigger an exception show how the exception is caught.\n:* When the integer overflow produces some value, print it.\n:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.\n:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.\n:* 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.\n\n", "solution": "2.1.1 :001 > a = 2**62 -1\n => 4611686018427387903 \n2.1.1 :002 > a.class\n => Fixnum \n2.1.1 :003 > (b = a + 1).class\n => Bignum \n2.1.1 :004 > (b-1).class\n => Fixnum\n"} {"title": "Intersecting number wheels", "language": "Ruby", "task": "A number wheel has:\n* A ''name'' which is an uppercase letter.\n* A set of ordered ''values'' which are either ''numbers'' or ''names''.\n\nA ''number'' is generated/yielded from a named wheel by:\n: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\":\n::1.a If the value is a number, yield it.\n::1.b If the value is a name, yield the next value from the named wheel\n::1.c Advance the position of this wheel.\n\nGiven the wheel\n: A: 1 2 3\nthe number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...\n\n'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the \nfirst named wheel is assumed to be the one that values are generated from.\n\n;Examples:\nGiven the wheels:\n A: 1 B 2\n B: 3 4\nThe series of numbers generated starts:\n 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...\n\nThe intersections of number wheels can be more complex, (and might loop forever),\nand wheels may be multiply connected. \n\n'''Note:''' If a named wheel is referenced more than \nonce by one or many other wheels, then there is only one position of the wheel \nthat is advanced by each and all references to it.\n\nE.g.\n A: 1 D D\n D: 6 7 8\n Generates:\n 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... \n\n;Task:\nGenerate and show the first twenty terms of the sequence of numbers generated \nfrom these groups:\n\n Intersecting Number Wheel group:\n A: 1 2 3\n \n Intersecting Number Wheel group:\n A: 1 B 2\n B: 3 4\n \n Intersecting Number Wheel group:\n A: 1 D D\n D: 6 7 8\n \n Intersecting Number Wheel group:\n A: 1 B C\n B: 3 4\n C: 5 B\n\nShow your output here, on this page.\n\n\n", "solution": "groups = [{A: [1, 2, 3]},\n {A: [1, :B, 2], B: [3, 4]},\n {A: [1, :D, :D], D: [6, 7, 8]},\n {A: [1, :B, :C], B: [3, 4], C: [5, :B]} ]\n\ngroups.each do |group|\n p group\n wheels = group.transform_values(&:cycle) \n res = 20.times.map do\n el = wheels[:A].next\n el = wheels[el].next until el.is_a?(Integer)\n el\n end\n puts res.join(\" \"),\"\"\nend\n"} {"title": "Inverted syntax", "language": "Ruby", "task": "'''Inverted syntax with conditional expressions'''\n\nIn traditional syntax conditional expressions are usually shown before the action within a statement or code block:\n\n IF raining=true THEN needumbrella=true \n\nIn inverted syntax, the action is listed before the conditional expression in the statement or code block:\n\n needumbrella=true IF raining=true \n\n'''Inverted syntax with assignment'''\n\nIn traditional syntax, assignments are usually expressed with the variable appearing before the expression:\n\n a = 6\n\nIn inverted syntax, the expression appears before the variable:\n 6 = a\n\n'''Task'''\n\nThe task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.\n", "solution": "# Raise ArgumentError if n is negative.\nif n < 0 then raise ArgumentError, \"negative n\" end\nraise ArgumentError, \"negative n\" if n < 0\n\n# Exit 1 unless we can call Process.fork.\nunless Process.respond_to? :fork then exit 1 end\nexit 1 unless Process.respond_to? :fork\n\n# Empty an array, printing each element.\nwhile ary.length > 0 do puts ary.shift end\nputs ary.shift while ary.length > 0\n\n# Another way to empty an array, printing each element.\nuntil ary.empty? do puts ary.shift end\nputs ary.shift until ary.empty?"} {"title": "Isograms and heterograms", "language": "Ruby", "task": "Definitions\nFor 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.\n\nA '''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'''.\n\n\n;Examples\n''caucasus'' is a '''2-isogram''' because the letters c, a, u and s all occur twice.\n\n''atmospheric'' is a '''heterogram''' because all its letters are used once only.\n\n\n;Task\nUsing '''unixdict.txt''' and ignoring capitalization:\n\n\n'''1)''' Find and display here all words which are '''n-isograms''' where '''n > 1'''.\n\nPresent the results as a single list but sorted as follows:\n\na. By decreasing order of '''n''';\n\nb. Then by decreasing order of word length;\n\nc. Then by ascending lexicographic order.\n\n'''2)''' Secondly, find and display here all words which are '''heterograms''' and have more than '''10''' characters.\n\nAgain present the results as a single list but sorted as per b. and c. above.\n\n\n;Reference\n\n* Wikipedia: Heterogram\n\n\n", "solution": "words = File.readlines(\"unixdict.txt\", chomp: true)\n\nisograms = words.group_by do |word|\n char_counts = word.downcase.chars.tally.values\n char_counts.first if char_counts.uniq.size == 1\nend\nisograms.delete(nil)\nisograms.transform_values!{|ar| ar.sort_by{|word| [-word.size, word]} }\n\nkeys = isograms.keys.sort.reverse\nkeys.each{|k| puts \"(#{isograms[k].size}) #{k}-isograms: #{isograms[k]} \" if k > 1 }\n\nmin_chars = 10\nlarge_heterograms = isograms[1].select{|word| word.size > min_chars }\nputs \"\" , \"(#{large_heterograms.size}) heterograms with more than #{min_chars} chars:\"\nputs large_heterograms\n"} {"title": "Isqrt (integer square root) of X", "language": "Ruby", "task": "Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a\nreal non-negative number.\n\nOften '''X''' is actually a non-negative integer.\n\nFor the purposes of this task, '''X''' can be an integer or a real number, but if it\nsimplifies things in your computer programming language, assume it's an integer.\n\n\nOne of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or\nprimes) up to the \n X of that\ninteger, either to find the factors of that integer, or to determine primality.\n\n\nAn alternative method for finding the '''Isqrt''' of a number is to\ncalculate: floor( sqrt(X) ) \n::* where '''sqrt''' is the square root function for non-negative real numbers, and\n::* where '''floor''' is the floor function for real numbers.\n\n\nIf the hardware supports the computation of (real) square roots, the above method might be a faster method for\nsmall numbers that don't have very many significant (decimal) digits.\n\nHowever, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support.\n\n\n;Pseudo-code using quadratic residue:\nFor this task, the integer square root of a non-negative number will be computed using a version\nof ''quadratic residue'', which has the advantage that no ''floating point'' calculations are\nused, only integer arithmetic. \n\nFurthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions.\n\nThe disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.\n\n\nPseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers):\n q <-- 1 /*initialize Q to unity. */\n /*find a power of 4 that's greater than X.*/\n perform while q <= x /*perform while Q <= X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n /*Q is now greater than X.*/\n z <-- x /*set Z to the value of X.*/\n r <-- 0 /*initialize R to zero. */\n perform while q > 1 /*perform while Q > unity. */\n q <-- q / 4 /*integer divide by four. */\n t <-- z - r - q /*compute value of T. */\n r <-- r / 2 /*integer divide by two. */\n if t >= 0 then do \n z <-- t /*set Z to value of T. */\n r <-- r + q /*compute new value of R. */\n end\n end /*perform*/\n /*R is now the Isqrt(X). */\n \n /* Sidenote: Also, Z is now the remainder after square root (i.e. */\n /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */\n\nAnother version for the (above) 1st '''perform''' is:\n perform until q > X /*perform until Q > X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n\n\nInteger square roots of some values:\n Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9\n Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10\n Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10\n Isqrt( 3) is 1 Isqrt(63) is 7\n Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10\n Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11\n Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11\n Isqrt( 7) is 2 Isqrt(67) is 8\n Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11\n Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12\n Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12\n\n\n;Task:\nCompute and show all output here (on this page) for:\n::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format.\n::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format.\n::* use commas in the displaying of larger numbers.\n\n\nYou can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.\nIf your computer programming language only supports smaller integers, show what you can.\n\n\n;Related tasks:\n:* sequence of non-squares\n:* integer roots\n:* square root by hand\n\n", "solution": "module Commatize\n refine Integer do\n def commatize\n self.to_s.gsub( /(\\d)(?=\\d{3}+(?:\\.|$))(\\d{3}\\..*)?/, \"\\\\1,\\\\2\")\n end\n end\nend\n\nusing Commatize\ndef isqrt(x)\n q, r = 1, 0\n while (q <= x) do q <<= 2 end\n while (q > 1) do\n q >>= 2; t = x-r-q; r >>= 1\n if (t >= 0) then x, r = t, r+q end\n end\n r\nend\n\nputs (0..65).map{|n| isqrt(n) }.join(\" \")\n\n1.step(73, 2) do |n|\n print \"#{n}:\\t\"\n puts isqrt(7**n).commatize\nend\n"} {"title": "Iterated digits squaring", "language": "Ruby", "task": "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:\n15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89\n7 -> 49 -> 97 -> 130 -> 10 -> 1\n\nAn example in Python:\n\n>>> step = lambda x: sum(int(d) ** 2 for d in str(x))\n>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))\n>>> [iterate(x) for x in xrange(1, 20)]\n[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]\n\n\n;Task:\n: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.\nOr, for much less credit - (showing that your algorithm and/or language is slow):\n: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.\n\nThis problem derives from the Project Euler problem 92.\n\nFor a quick algorithm for this task see the talk page\n\n\n;Related tasks:\n* [[Combinations with repetitions]]\n* [[Digital root]]\n* [[Digital root/Multiplicative digital root]]\n\n", "solution": "# Count how many number chains for Natural Numbers < 10**d end with a value of 1.\ndef iterated_square_digit(d)\n f = Array.new(d+1){|n| (1..n).inject(1, :*)} #Some small factorials\n g = -> (n) { res = n.digits.sum{|d| d*d} \n res==89 ? 0 : res }\n \n #An array: table[n]==0 means that n translates to 89 and 1 means that n translates to 1\n table = Array.new(d*81+1){|n| n.zero? ? 1 : (i=g.call(n))==89 ? 0 : i}\n table.collect!{|n| n = table[n] while n>1; n}\n z = 0 #Running count of numbers translating to 1\n [*0..9].repeated_combination(d) do |rc| #Iterate over unique digit combinations\n next if table[rc.inject(0){|g,n| g+n*n}].zero? #Count only ones\n nn = [0] * 10 #Determine how many numbers this digit combination corresponds to\n rc.each{|n| nn[n] += 1}\n z += nn.inject(f[d]){|gn,n| gn / f[n]} #Add to the count of numbers terminating in 1\n end\n puts \"\\nd=(#{d}) in the range 1 to #{10**d-1}\",\n \"#{z} numbers produce 1 and #{10**d-1-z} numbers produce 89\"\nend\n\n[8, 11, 14, 17].each do |d|\n t0 = Time.now\n iterated_square_digit(d)\n puts \" #{Time.now - t0} sec\"\nend"} {"title": "JSON", "language": "Ruby", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": "require 'json'\n\nruby_obj = JSON.parse('{\"blue\": [1, 2], \"ocean\": \"water\"}')\nputs ruby_obj\n\nruby_obj[\"ocean\"] = { \"water\" => [\"fishy\", \"salty\"] }\nputs JSON.generate(ruby_obj)\nputs JSON.pretty_generate(ruby_obj)"} {"title": "Jacobi symbol", "language": "Ruby from Crystal", "task": "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)\n* (a | p) 1 if a is a square (mod p)\n* (a | p) -1 if a is not a square (mod p)\n* (a | p) 0 if a 0 \n\nIf n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).\n\n;Task:\nCalculate the Jacobi symbol (a | n).\n\n;Reference:\n* Wikipedia article on Jacobi symbol.\n\n", "solution": "def jacobi(a, n)\n raise ArgumentError.new \"n must b positive and odd\" if n < 1 || n.even?\n res = 1\n until (a %= n) == 0\n while a.even?\n a >>= 1\n res = -res if [3, 5].include? n % 8\n end\n a, n = n, a\n res = -res if [a % 4, n % 4] == [3, 3]\n end\n n == 1 ? res : 0\nend\n\nputs \"Jacobian symbols for jacobi(a, n)\"\nputs \"n\\\\a 0 1 2 3 4 5 6 7 8 9 10\"\nputs \"------------------------------------\"\n1.step(to: 17, by: 2) do |n|\n printf(\"%2d \", n)\n (0..10).each { |a| printf(\" % 2d\", jacobi(a, n)) }\n puts\nend"} {"title": "Jacobsthal numbers", "language": "Ruby", "task": "'''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.\n\n \n J0 = 0\n J1 = 1\n Jn = Jn-1 + 2 x Jn-2\n\n\nTerms may be calculated directly using one of several possible formulas:\n \n Jn = ( 2n - (-1)n ) / 3\n \n\n\n'''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'''.\n\nTerms may be calculated directly using one of several possible formulas:\n \n JLn = 2n + (-1)n\n\n\n'''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''.\n\n\n'''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime.\n\n\n\n;Task\n* Find and display the first 30 '''Jacobsthal numbers'''\n* Find and display the first 30 '''Jacobsthal-Lucas numbers'''\n* Find and display the first 20 '''Jacobsthal oblong numbers'''\n* Find and display at least the first 10 '''Jacobsthal primes'''\n\n\n\n;See also\n;* Wikipedia: Jacobsthal number\n;* Numbers Aplenty - Jacobsthal number\n;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers)\n;* OEIS:A014551 - Jacobsthal-Lucas numbers.\n;* OEIS:A084175 - Jacobsthal oblong numbers\n;* OEIS:A049883 - Primes in the Jacobsthal sequence\n;* Related task: Fibonacci sequence\n;* Related task: Leonardo numbers\n\n\n\n\n", "solution": "require 'prime'\n\ndef jacobsthal(n) = (2**n + n[0])/3\ndef jacobsthal_lucas(n) = 2**n + (-1)**n\ndef jacobsthal_oblong(n) = jacobsthal(n) * jacobsthal(n+1)\n\nputs \"First 30 Jacobsthal numbers:\"\nputs (0..29).map{|n| jacobsthal(n) }.join(\" \")\n\nputs \"\\nFirst 30 Jacobsthal-Lucas numbers: \"\nputs (0..29).map{|n| jacobsthal_lucas(n) }.join(\" \")\n\nputs \"\\nFirst 20 Jacobsthal-Oblong numbers: \"\nputs (0..19).map{|n| jacobsthal_oblong(n) }.join(\" \")\n\nputs \"\\nFirst 10 prime Jacobsthal numbers: \"\nres = (0..).lazy.filter_map do |i|\n j = jacobsthal(i) \n j if j.prime?\nend\nputs res.take(10).force.join(\" \")\n"} {"title": "Jaro similarity", "language": "Ruby", "task": "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.\n\n\n;;Definition\n\nThe Jaro similarity d_j of two given strings s_1 and s_2 is\n\n: d_j = \\left\\{\n\n\\begin{array}{l l}\n 0 & \\text{if }m = 0\\\\\n \\frac{1}{3}\\left(\\frac{m}{|s_1|} + \\frac{m}{|s_2|} + \\frac{m-t}{m}\\right) & \\text{otherwise} \\end{array} \\right.\n\nWhere:\n\n* m is the number of ''matching characters'';\n* t is half the number of ''transpositions''.\n\n\nTwo 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.\n\nEach 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.\n\n\n;;Example\n\nGiven the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find:\n\n* m = 4\n* |s_1| = 6\n* |s_2| = 5\n* t = 0\n\n\nWe find a Jaro score of:\n\n: d_j = \\frac{1}{3}\\left(\\frac{4}{6} + \\frac{4}{5} + \\frac{4-0}{4}\\right) = 0.822\n\n\n;Task\n\nImplement the Jaro algorithm and show the similarity scores for each of the following pairs:\n\n* (\"MARTHA\", \"MARHTA\")\n* (\"DIXON\", \"DICKSONX\")\n* (\"JELLYFISH\", \"SMELLYFISH\")\n\n\n; See also\n* Jaro-Winkler distance on Wikipedia.\n\n", "solution": "def jaro(s, t)\n return 1.0 if s == t\n \n s_len = s.size\n t_len = t.size\n match_distance = ([s_len, t_len].max / 2) - 1\n \n s_matches = []\n t_matches = []\n matches = 0.0\n \n s_len.times do |i|\n j_start = [0, i-match_distance].max\n j_end = [i+match_distance, t_len-1].min\n \n (j_start..j_end).each do |j|\n t_matches[j] && next\n s[i] == t[j] || next\n s_matches[i] = true\n t_matches[j] = true\n matches += 1.0\n break\n end\n end\n \n return 0.0 if matches == 0.0\n \n k = 0\n transpositions = 0.0\n s_len.times do |i|\n s_matches[i] || next\n k += 1 until t_matches[k]\n s[i] == t[k] || (transpositions += 1.0)\n k += 1\n end\n \n ((matches / s_len) +\n (matches / t_len) +\n ((matches - transpositions/2.0) / matches)) / 3.0\nend\n\n%w(\n MARTHA MARHTA\n DIXON DICKSONX\n JELLYFISH SMELLYFISH\n).each_slice(2) do |s,t|\n puts \"jaro(#{s.inspect}, #{t.inspect}) = #{'%.10f' % jaro(s, t)}\"\nend"} {"title": "Jewels and stones", "language": "Ruby", "task": "Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by this problem.\n\n\n\n", "solution": "stones, jewels = \"aAAbbbb\", \"aA\"\n\nstones.count(jewels) # => 3\n"} {"title": "Juggler sequence", "language": "Ruby", "task": "Background of the '''juggler sequence''':\n\nJuggler 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.\n\n\n;Description\nA 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: \n\n a[k + 1] = floor(a[k] ^ 0.5) if a[k] is even ''' ''or'' ''' \n a[k + 1] = floor(a[k] ^ 1.5) if a[k] is odd \n\nIf 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.\n\n\n;Task:\nCompute and show here the following statistics for juggler sequences with an initial term of a[n] where n is between '''20''' and '''39''' inclusive:\n\n* l[n] - the number of terms needed to reach 1.\n* h[n] - the maximum value reached in that sequence.\n* i[n] - the index of the term (starting from 0) at which the maximum is (first) reached.\n\nIf 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:\n\n113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827\n\nThose with fast languages and fast machines may also like to try their luck at n = 7110201.\n\nHowever, as h[n] for most of these numbers is thousands or millions of digits long, show instead of h[n]:\n\n* d[n] - the number of digits in h[n]\n\nThe results can be (partially) verified against the table here.\n \n\n;Related tasks:\n* [[Hailstone sequence]]\n* [[Yellowstone sequence]]\n* [[Isqrt_(integer_square_root)_of_X]]\n\n\n;See also:\n* [[oeis:A007320]] Number of steps needed for Juggler sequence started at n to reach 1 \t\t\n* [[oeis:A094716]] Largest value in the Juggler sequence started at n\n\n", "solution": "def juggler(k) = k.even? ? Integer.sqrt(k) : Integer.sqrt(k*k*k)\n\n(20..39).chain([113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915]).each do |k|\n k1 = k\n l = h = i = 0\n until k == 1 do\n h, i = k, l if k > h\n l += 1\n k = juggler(k)\n end\n if k1 < 40 then\n puts \"#{k1}: l[n] = #{l}, h[n] = #{h}, i[n] = #{i}\"\n else\n puts \"#{k1}: l[n] = #{l}, d[n] = #{h.to_s.size}, i[n] = #{i}\"\n end\nend\n"} {"title": "Julia set", "language": "Ruby from AWK", "task": "Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* Mandelbrot Set\n\n", "solution": "def julia(c_real, c_imag)\n puts Complex(c_real, c_imag)\n -1.0.step(1.0, 0.04) do |v|\n puts -1.4.step(1.4, 0.02).map{|h| judge(c_real, c_imag, h, v)}.join\n end\nend\n\ndef judge(c_real, c_imag, x, y)\n 50.times do\n z_real = (x * x - y * y) + c_real\n z_imag = x * y * 2 + c_imag\n return \" \" if z_real**2 > 10000\n x, y = z_real, z_imag\n end\n \"#\"\nend\n\njulia(-0.8, 0.156)"} {"title": "Jump anywhere", "language": "Ruby", "task": "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.\n\nThis task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. \nFor 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. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. \nThis 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!\n\n* Some languages can ''go to'' any global label in a program.\n* Some languages can break multiple function calls, also known as ''unwinding the call stack''.\n* 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).\n\nThese jumps are not all alike. \nA simple ''goto'' never touches the call stack. \nA continuation saves the call stack, so you can continue a function call after it ends.\n\n\n;Task:\nUse your language to demonstrate the various types of jumps that it supports. \n\nBecause the possibilities vary by language, this task is not specific. \nYou have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].\n\n", "solution": "Ruby programs almost never use continuations. [[MRI]] copies the call stack when it saves or calls a continuation, so continuations are slow.\n\nThe next example abuses a continuation to solve [[FizzBuzz#Ruby]]. It is slower and more confusing than an ordinary loop.\n"} {"title": "Kaprekar numbers", "language": "Ruby", "task": "A positive integer is a Kaprekar number if:\n* It is '''1''' (unity)\n* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. \nNote that a split resulting in a part consisting purely of 0s is not valid, \nas 0 is not considered positive.\n\n\n;Example Kaprekar numbers:\n* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.\n* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....\n\n\n;Example process:\n10000 (1002) splitting from left to right:\n* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.\n* 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.\n\n\n;Task:\nGenerate and show all Kaprekar numbers less than 10,000. \n\n\n;Extra credit:\nOptionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.\n\n\n;Extra extra credit:\nThe concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); \nif you can, show that Kaprekar numbers exist in other bases too. \n\n\nFor this purpose, do the following:\n* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);\n* Display each of them in base 10 representation;\n* 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. \n \nFor 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\n\n\n;Reference:\n* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version\n\n\n;Related task:\n* [[Casting out nines]]\n\n", "solution": "def kaprekar(n, base = 10)\n return [1, 1, 1, \"\"] if n == 1 \n return if n*(n-1) % (base-1) != 0 # casting out nine\n sqr = (n ** 2).to_s(base)\n (1...sqr.length).each do |i|\n a = sqr[0 ... i]\n b = sqr[i .. -1]\n break if b.delete(\"0\").empty?\n sum = a.to_i(base) + b.to_i(base)\n return n.to_s(base), sqr, a, b if sum == n\n end\n nil\nend\n\ncount = 0\n1.upto(10_000 - 1) do |i| \n if result = kaprekar(i)\n puts \"%4d %8d %s + %s\" % result\n count += 1\n end\nend\n\n10_000.upto(1_000_000 - 1) {|i| count += 1 if kaprekar(i)}\nputs \"#{count} kaprekar numbers under 1,000,000\"\n\nputs \"\\nbase17 kaprekar numbers under (base10)1,000,000\"\nbase = 17\n1.upto(1_000_000) do |decimal|\n if result = kaprekar(decimal, base)\n puts \"%7s %5s %9s %s + %s\" % [decimal, *result]\n end\nend"} {"title": "Kernighans large earthquake problem", "language": "Ruby", "task": "Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.\n\n;Problem:\nYou 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.\n\nExample lines from the file would be lines like:\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n\n;Task:\n* Create a program or script invocation to find all the events with magnitude greater than 6\n* Assuming an appropriate name e.g. \"data.txt\" for the file:\n:# Either: Show how your program is invoked to process a data file of that name.\n:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).\n\n", "solution": "ruby -nae \"$F[2].to_f > 6 && print\" data.txt\n\nA more interesting problem. Print only the events whose magnitude is above average.\n\nContents of the file:\n\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n2000-02-02 Foo 7.7\n1959-08-08 Bar 6.2\n1849-09-09 Pym 9.0\n\nThe command:\n\nruby -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\n\nOutput:\n\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n2000-02-02 Foo 7.7\n1849-09-09 Pym 9.0\n\n\n"} {"title": "Keyboard input/Obtain a Y or N response", "language": "Ruby", "task": "Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. \n\nThe response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.\n\n", "solution": "def yesno\n begin\n system(\"stty raw -echo\")\n str = STDIN.getc\n ensure\n system(\"stty -raw echo\")\n end\n if str == \"Y\"\n return true\n elsif str == \"N\"\n return false\n else\n raise \"Invalid character.\"\n end\nend\n"} {"title": "Knight's tour", "language": "Ruby", "task": "Task\nProblem: 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.\n\nInput 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.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "class Board\n Cell = Struct.new(:value, :adj) do\n def self.end=(end_val)\n @@end = end_val\n end\n \n def try(seq_num)\n self.value = seq_num\n return true if seq_num==@@end\n a = []\n adj.each_with_index do |cell, n|\n a << [wdof(cell.adj)*10+n, cell] if cell.value.zero?\n end\n a.sort.each {|_, cell| return true if cell.try(seq_num+1)}\n self.value = 0\n false\n end\n \n def wdof(adj)\n adj.count {|cell| cell.value.zero?}\n end\n end\n \n def initialize(rows, cols)\n @rows, @cols = rows, cols\n unless defined? ADJACENT # default move (Knight)\n eval(\"ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]]\")\n end\n frame = ADJACENT.flatten.map(&:abs).max\n @board = Array.new(rows+frame) do |i|\n Array.new(cols+frame) do |j|\n (i= n and M, the number of items is unknown until the end.\nThis 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).\n\n\n;The algorithm:\n:* Select the first n items as the sample as they become available;\n:* 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.\n:* Repeat 2nd step for any subsequent items.\n\n\n;The Task:\n:* 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.\n:* 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.\n:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:\n:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.\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.\n\n\nNote: A class taking n and generating a callable instance/function might also be used.\n\n\n;Reference:\n* The Art of Computer Programming, Vol 2, 3.4.2 p.142\n\n\n;Related tasks: \n* [[One of n lines in a file]] \n* [[Accumulator factory]]\n\n", "solution": "def s_of_n_creator(n)\n sample = []\n i = 0\n Proc.new do |item|\n i += 1\n if i <= n\n sample << item\n elsif rand(i) < n\n sample[rand(n)] = item\n end\n sample\n end\nend\n\nfrequency = Array.new(10,0)\n100_000.times do\n s_of_n = s_of_n_creator(3)\n sample = nil\n (0..9).each {|digit| sample = s_of_n[digit]}\n sample.each {|digit| frequency[digit] += 1}\nend\n\n(0..9).each {|digit| puts \"#{digit}\\t#{frequency[digit]}\"}"} {"title": "Kolakoski sequence", "language": "Ruby", "task": "The natural numbers, (excluding zero); with the property that:\n: ''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''.\n\n;Example:\nThis is ''not'' a Kolakoski sequence:\n1,1,2,2,2,1,2,2,1,2,...\nIts 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:\n\n: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...\n\nThe above gives the RLE of:\n2, 3, 1, 2, 1, ...\n\nThe original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.\n\n;Creating a Kolakoski sequence:\n\nLets 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,....\n\n# We start the sequence s with the first item from the cycle c: 1\n# 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. \nWe will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.\n\nWe started s with 1 and therefore s[k] states that it should appear only the 1 time.\n\nIncrement k\nGet the next item from c and append it to the end of sequence s. s will then become: 1, 2\nk 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\nIncrement k\nAppend the next item from the cycle to the list: 1, 2,2, 1\nk 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\nincrement k\n\n...\n\n'''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.\n\n;Task:\n# 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.\n# 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.\n# 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).\n# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 20 members of the sequence generated from (2, 1)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)\n# Check the sequence againt its RLE.\n(There are rules on generating Kolakoski sequences from this method that are broken by the last example)\n\n", "solution": "def create_generator(ar)\n Enumerator.new do |y|\n cycle = ar.cycle\n s = []\n loop do\n t = cycle.next\n s.push(t)\n v = s.shift\n y << v\n (v-1).times{s.push(t)}\n end\n end\nend\n\ndef rle(ar)\n ar.slice_when{|a,b| a != b}.map(&:size)\nend\n\n[[20, [1,2]], \n [20, [2,1]], \n [30, [1,3,1,2]],\n [30, [1,3,2,1]]].each do |num,ar|\n puts \"\\nFirst #{num} of the sequence generated by #{ar.inspect}:\"\n p res = create_generator(ar).take(num)\n puts \"Possible Kolakoski sequence? #{res.join.start_with?(rle(res).join)}\"\nend"} {"title": "Lah numbers", "language": "Ruby", "task": "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.\n\nUnsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.\n\nLah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.\n\nLah numbers obey the identities and relations:\n L(n, 0), L(0, k) = 0 # for n, k > 0\n L(n, n) = 1\n L(n, 1) = n!\n L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers\n ''or''\n L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers\n\n;Task:\n:* 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.\n\n:* 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).\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Lah number'''\n:* '''OEIS:A105278 - Unsigned Lah numbers'''\n:* '''OEIS:A008297 - Signed Lah numbers'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Stirling numbers of the second kind'''\n:* '''Bell numbers'''\n\n\n", "solution": "def fact(n) = n.zero? ? 1 : 1.upto(n).inject(&:*)\n\ndef lah(n, k)\n case k\n when 1 then fact(n)\n when n then 1\n when (..1),(n..) then 0\n else n<1 ? 0 : (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k)\n end\nend\n \nr = (0..12)\nputs \"Unsigned Lah numbers: L(n, k):\"\nputs \"n/k #{r.map{|n| \"%11d\" % n}.join}\"\n\nr.each do |row|\n print \"%-4s\" % row\n puts \"#{(0..row).map{|col| \"%11d\" % lah(row,col)}.join}\"\nend\n\nputs \"\\nMaximum value from the L(100, *) row:\";\nputs (1..100).map{|a| lah(100,a)}.max\n"} {"title": "Largest int from concatenated ints", "language": "Ruby from Tcl", "task": "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.\n\nUse the following two sets of integers as tests and show your program output here.\n\n:::::* {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* {54, 546, 548, 60}\n\n\n;Possible algorithms:\n# A solution could be found by trying all combinations and return the best. \n# 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.\n# 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.\n\n\n;See also:\n* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?\n* Constructing the largest number possible by rearranging a list\n\n", "solution": "def icsort nums\n nums.sort { |x, y| \"#{y}#{x}\" <=> \"#{x}#{y}\" }\nend\n\n[[54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4]].each do |c|\n p c # prints nicer in Ruby 1.8\n puts icsort(c).join\nend"} {"title": "Largest number divisible by its digits", "language": "Ruby", "task": "Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the\n(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.\n\n\nNote that the digit zero (0) can not be in the number as integer division by zero is undefined. \n\nThe digits must all be unique so a base ten number will have at most '''9''' digits.\n\nFeel 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.)\n\n\n;Stretch goal:\nDo the same thing for hexadecimal.\n\n\n;Related tasks:\n:* gapful numbers.\n:* palindromic gapful numbers. \n\n\n;Also see:\n:* The OEIS sequence: A115569: Lynch-Bell numbers. \n\n", "solution": "magic_number = 9*8*7\ndiv = 9876432.div(magic_number) * magic_number\ncandidates = div.step(0, -magic_number)\n\nres = candidates.find do |c|\n digits = c.digits\n (digits & [0,5]).empty? && digits == digits.uniq \nend\n\nputs \"Largest decimal number is #{res}\""} {"title": "Largest number divisible by its digits", "language": "Ruby from Crystal from Kotlin", "task": "Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the\n(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.\n\n\nNote that the digit zero (0) can not be in the number as integer division by zero is undefined. \n\nThe digits must all be unique so a base ten number will have at most '''9''' digits.\n\nFeel 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.)\n\n\n;Stretch goal:\nDo the same thing for hexadecimal.\n\n\n;Related tasks:\n:* gapful numbers.\n:* palindromic gapful numbers. \n\n\n;Also see:\n:* The OEIS sequence: A115569: Lynch-Bell numbers. \n\n", "solution": "def divByAll(num, digits)\n digits.all? { |digit| num % digit.to_i(16) == 0 }\nend\n\nmagic = 15 * 14 * 13 * 12 * 11\nhigh = (0xfedcba987654321 / magic) * magic\n\nhigh.step(magic, -magic) do |i|\n s = i.to_s(16) # always generates lower case a-f\n next if s.include? \"0\" # can't contain '0'\n sd = s.chars.uniq\n next if sd.size != s.size # digits must be unique\n (puts \"Largest hex number is #{i.to_s(16)}\"; break) if divByAll(i, sd)\nend"} {"title": "Largest proper divisor of n", "language": "Ruby", "task": "a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.\n\n", "solution": "require 'prime'\n\ndef a(n)\n return 1 if n == 1 || n.prime?\n (n/2).downto(1).detect{|d| n.remainder(d) == 0}\nend\n\n(1..100).map{|n| a(n).to_s.rjust(3)}.each_slice(10){|slice| puts slice.join}\n"} {"title": "Last Friday of each month", "language": "Ruby", "task": "Write a program or a script that returns the date of the last Fridays of each month of a given year. \n\nThe year may be given through any simple input method in your language (command line, std in, etc).\n\n\nExample of an expected output:\n./last_fridays 2012\n2012-01-27\n2012-02-24\n2012-03-30\n2012-04-27\n2012-05-25\n2012-06-29\n2012-07-27\n2012-08-31\n2012-09-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n\n;Related tasks\n* [[Five weekends]]\n* [[Day of the week]]\n* [[Find the last Sunday of each month]]\n\n", "solution": "require 'date'\n\ndef last_friday(year, month)\n # Last day of month: Date.new interprets a negative number as a relative month/day from the end of year/month.\n d = Date.new(year, month, -1)\n d -= (d.wday - 5) % 7 # Subtract days after Friday.\nend\n\nyear = Integer(ARGV.shift)\n(1..12).each {|month| puts last_friday(year, month)}"} {"title": "Last letter-first letter", "language": "Ruby", "task": "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. \n\n\nFor example, with \"animals\" as the category,\n\nChild 1: dog \nChild 2: goldfish\nChild 1: hippopotamus\nChild 2: snake\n...\n\n\n\n;Task:\nTake 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. \n\nNo Pokemon name is to be repeated.\n\n\naudino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\ncresselia croagunk darmanitan deino emboar emolga exeggcute gabite\ngirafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\nkricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\nnosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\nsealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\ntyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\n\n\n\nExtra brownie points for dealing with the full list of 646 names.\n\n", "solution": "class LastL_FirstL\n def initialize(names)\n @names = names.dup\n @first = names.group_by {|name| name[0]}\n @sequences = []\n end\n \n def add_name(seq)\n last_letter = seq[-1][-1]\n potentials = @first.include?(last_letter) ? (@first[last_letter] - seq) : []\n if potentials.empty?\n @sequences << seq\n else\n potentials.each {|name| add_name(seq + [name])}\n end\n end\n \n def search\n @names.each {|name| add_name [name]}\n max = @sequences.max_by {|seq| seq.length}.length\n max_seqs = @sequences.select {|seq| seq.length == max}\n puts \"there are #{@sequences.length} possible sequences\"\n puts \"the longest is #{max} names long\"\n puts \"there are #{max_seqs.length} such sequences. one is:\"\n max_seqs.last.each_with_index {|name, idx| puts \" %2d %s\" % [idx+1, name]}\n end\nend\n\nnames = %w{\n audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\n cresselia croagunk darmanitan deino emboar emolga exeggcute gabite\n girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\n kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\n nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\n porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\n sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\n tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\n}\n\nlf = LastL_FirstL.new(names)\nlf.search"} {"title": "Latin Squares in reduced form", "language": "Ruby from D", "task": "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.\n\nFor 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.\n\nDemonstrate by:\n* displaying the four reduced Latin Squares of order 4.\n* 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.\n\n", "solution": "def printSquare(a)\n for row in a\n print row, \"\\n\"\n end\n print \"\\n\"\nend\n\ndef dList(n, start)\n start = start - 1 # use 0 based indexing\n a = Array.new(n) {|i| i}\n a[0], a[start] = a[start], a[0]\n a[1..] = a[1..].sort\n first = a[1]\n\n r = []\n recurse = lambda {|last|\n if last == first then\n # bottom of recursion, reached once for each permutation\n # test if permutation is deranged\n a[1..].each_with_index {|v, j|\n if j + 1 == v then\n return # no, ignore it\n end\n }\n # yes, save a copy with 1 based indexing\n b = a.map { |i| i + 1 }\n r << b\n return\n end\n\n i = last\n while i >= 1 do\n a[i], a[last] = a[last], a[i]\n recurse.call(last - 1)\n a[i], a[last] = a[last], a[i]\n i = i - 1\n end\n }\n\n recurse.call(n - 1)\n return r\nend\n\ndef reducedLatinSquares(n, echo)\n if n <= 0 then\n if echo then\n print \"[]\\n\\n\"\n end\n return 0\n end\n if n == 1 then\n if echo then\n print \"[1]\\n\\n\"\n end\n return 1\n end\n\n rlatin = Array.new(n) { Array.new(n, Float::NAN)}\n\n # first row\n for j in 0 .. n - 1\n rlatin[0][j] = j + 1\n end\n\n count = 0\n recurse = lambda {|i|\n rows = dList(n, i)\n\n for r in 0 .. rows.length - 1\n rlatin[i - 1] = rows[r].dup\n catch (:outer) do\n for k in 0 .. i - 2\n for j in 1 .. n - 1\n if rlatin[k][j] == rlatin[i - 1][j] then\n if r < rows.length - 1 then\n throw :outer\n end\n if i > 2 then\n return\n end\n end\n end\n end\n if i < n then\n recurse.call(i + 1)\n else\n count = count + 1\n if echo then\n printSquare(rlatin)\n end\n end\n end\n end\n }\n\n # remaining rows\n recurse.call(2)\n return count\nend\n\ndef factorial(n)\n if n == 0 then\n return 1\n end\n prod = 1\n for i in 2 .. n\n prod = prod * i\n end\n return prod\nend\n\nprint \"The four reduced latin squares of order 4 are:\\n\"\nreducedLatinSquares(4, true)\n\nprint \"The size of the set of reduced latin squares for the following orders\\n\"\nprint \"and hence the total number of latin squares of these orders are:\\n\"\nfor n in 1 .. 6\n size = reducedLatinSquares(n, false)\n f = factorial(n - 1)\n f = f * f * n * size\n print \"Order %d Size %-4d x %d! x %d! => Total %d\\n\" % [n, size, n, n - 1, f]\nend"} {"title": "Law of cosines - triples", "language": "Ruby", "task": "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:\n A2 + B2 - 2ABcos(g) = C2 \n\n;Specific angles:\nFor an angle of of '''90o''' this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of '''60o''' this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of '''120o''' this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* Restrain all sides to the integers '''1..13''' inclusive.\n* Show how many results there are for each of the three angles mentioned above.\n* Display results on this page.\n\n\nNote: Triangles with the same length sides but different order are to be treated as the same. \n\n;Optional Extra credit:\n* 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''.\n\n\n;Related Task\n* [[Pythagorean triples]]\n\n\n;See also:\n* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video\n\n", "solution": "grouped = (1..13).to_a.repeated_permutation(3).group_by do |a,b,c|\n sumaabb, ab = a*a + b*b, a*b\n case c*c\n when sumaabb then 90\n when sumaabb - ab then 60\n when sumaabb + ab then 120\n end\nend\n\ngrouped.delete(nil)\nres = grouped.transform_values{|v| v.map(&:sort).uniq }\n\nres.each do |k,v|\n puts \"For an angle of #{k} there are #{v.size} solutions:\"\n puts v.inspect, \"\\n\"\nend\n"} {"title": "Least common multiple", "language": "Ruby", "task": "Compute the least common multiple (LCM) of two integers.\n\nGiven ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. \n\n\n;Example:\nThe least common multiple of '''12''' and '''18''' is '''36''', because:\n:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and \n:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and \n:* there is no positive integer less than '''36''' that has both factors. \n\n\nAs a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.\n\n\nOne 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''.\n\nIf you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.\n\n\n;Related task\n:* greatest common divisor.\n\n\n;See also:\n* MathWorld entry: Least Common Multiple.\n* Wikipedia entry: Least common multiple.\n\n", "solution": "def gcd(m, n)\n m, n = n, m % n until n.zero?\n m.abs\nend\n\ndef lcm(*args)\n args.inject(1) do |m, n|\n return 0 if n.zero?\n (m * n).abs / gcd(m, n)\n end\nend\n\np lcm 12, 18, 22\np lcm 15, 14, -6, 10, 21"} {"title": "Left factorials", "language": "Ruby", "task": "'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; \nthe same notation can be confusingly seen being used for the two different definitions.\n\nSometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: \n:::::::* !''n''` \n:::::::* !''n'' \n:::::::* ''n''! \n\n\n(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)\n\n\nThis Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':\n\n::::: !n = \\sum_{k=0}^{n-1} k! \n\n:::: where\n\n::::: !0 = 0\n\n\n\n;Task\nDisplay the left factorials for:\n* zero through ten (inclusive)\n* 20 through 110 (inclusive) by tens\n\n\nDisplay the length (in decimal digits) of the left factorials for:\n* 1,000 through 10,000 (inclusive), by thousands.\n\n\n;Also see:\n* The OEIS entry: A003422 left factorials\n* The MathWorld entry: left factorial\n* The MathWorld entry: factorial sums\n* The MathWorld entry: subfactorial\n\n\n;Related task:\n* permutations/derangements (subfactorials)\n\n", "solution": "tens = 20.step(110, 10)\nthousands = 1000.step(10_000, 1000)\n\n10001.times do |n|\n lf = left_fact.next\n case n\n when 0..10, *tens\n puts \"!#{n} = #{lf}\"\n when *thousands\n puts \"!#{n} has #{lf.to_s.size} digits\"\n end\nend"} {"title": "Levenshtein distance", "language": "Ruby", "task": "{{Wikipedia}}\n\nIn 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. \n\n\n;Example:\nThe 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:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "module Levenshtein\n \n def self.distance(a, b)\n a, b = a.downcase, b.downcase\n costs = Array(0..b.length) # i == 0\n (1..a.length).each do |i|\n costs[0], nw = i, i - 1 # j == 0; nw is lev(i-1, j)\n (1..b.length).each do |j|\n costs[j], nw = [costs[j] + 1, costs[j-1] + 1, a[i-1] == b[j-1] ? nw : nw + 1].min, costs[j]\n end\n end\n costs[b.length]\n end\n \n def self.test\n %w{kitten sitting saturday sunday rosettacode raisethysword}.each_slice(2) do |a, b|\n puts \"distance(#{a}, #{b}) = #{distance(a, b)}\"\n end\n end\n \nend\n\nLevenshtein.test"} {"title": "Levenshtein distance/Alignment", "language": "Ruby from Tcl", "task": "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.\n\nAn 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:\n\n\nP-LACE\nPALACE\n\n\n\n;Task:\nWrite a function that shows the alignment of two strings for the corresponding levenshtein distance. \n\nAs an example, use the words \"rosettacode\" and \"raisethysword\".\n\nYou can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).\n\n", "solution": "require 'lcs'\n\ndef levenshtein_align(a, b)\n apos, bpos = LCS.new(a, b).backtrack2\n \n c = \"\"\n d = \"\"\n x0 = y0 = -1\n dx = dy = 0\n apos.zip(bpos) do |x,y|\n diff = x + dx - y - dy\n if diff < 0\n dx -= diff\n c += \"-\" * (-diff)\n elsif diff > 0\n dy += diff\n d += \"-\" * diff\n end\n c += a[x0+1..x]\n x0 = x\n d += b[y0+1..y]\n y0 = y\n end\n \n c += a[x0+1..-1]\n d += b[y0+1..-1]\n diff = a.length + y0 - b.length - x0\n if diff < 0\n c += \"-\" * (-diff)\n elsif diff > 0\n d += \"-\" * diff\n end\n [c, d]\nend\n\nputs levenshtein_align(\"rosettacode\", \"raisethysword\")"} {"title": "List rooted trees", "language": "Ruby from Java", "task": "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.\n\nIf we use a matching pair of parentheses to represent a bag, the ways are:\n\nFor 1 bag, there's one way:\n ()\t<- a bag\n\nfor 2 bags, there's one way:\n (())\t<- one bag in another\n\nfor 3 bags, there are two:\n ((())) <- 3 bags nested Russian doll style\n (()()) <- 2 bags side by side, inside the third\n\nfor 4 bags, four:\n (()()())\n ((())())\n ((()()))\n (((())))\n\nNote that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.\n\nIt'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.\n\n\n;Task: \nWrite 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.\n\nThis 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.\n\nAs an example output, run 5 bags. There should be 9 ways.\n\n", "solution": "TREE_LIST = []\nOFFSET = []\n\nfor i in 0..31\n if i == 1 then\n OFFSET << 1\n else\n OFFSET << 0\n end\nend\n\ndef append(t)\n TREE_LIST << (1 | (t << 1))\nend\n\ndef show(t, l)\n while l > 0\n l = l - 1\n if t % 2 == 1 then\n print '('\n else\n print ')'\n end\n t = t >> 1\n end\nend\n\ndef listTrees(n)\n for i in OFFSET[n] .. OFFSET[n + 1] - 1\n show(TREE_LIST[i], n * 2)\n print \"\\n\"\n end\nend\n\ndef assemble(n, t, sl, pos, rem)\n if rem == 0 then\n append(t)\n return\n end\n\n if sl > rem then\n sl = rem\n pos = OFFSET[sl]\n elsif pos >= OFFSET[sl + 1] then\n sl = sl - 1\n if sl == 0 then\n return\n end\n pos = OFFSET[sl]\n end\n\n assemble(n, t << (2 * sl) | TREE_LIST[pos], sl, pos, rem - sl)\n assemble(n, t, sl, pos + 1, rem)\nend\n\ndef makeTrees(n)\n if OFFSET[n + 1] != 0 then\n return\n end\n if n > 0 then\n makeTrees(n - 1)\n end\n assemble(n, 0, n - 1, OFFSET[n - 1], n - 1)\n OFFSET[n + 1] = TREE_LIST.length()\nend\n\ndef test(n)\n if n < 1 || n > 12 then\n raise ArgumentError.new(\"Argument must be between 1 and 12\")\n end\n\n append(0)\n\n makeTrees(n)\n print \"Number of %d-trees: %d\\n\" % [n, OFFSET[n + 1] - OFFSET[n]]\n listTrees(n)\nend\n\ntest(5)"} {"title": "Long literals, with continuations", "language": "Ruby", "task": "This task is about writing a computer program that has long literals (character\nliterals that may require specifying the words/tokens on more than one (source)\nline, either with continuations or some other method, such as abutments or\nconcatenations (or some other mechanisms).\n\n\nThe literal is to be in the form of a \"list\", a literal that contains many\nwords (tokens) separated by a blank (space), in this case (so as to have a\ncommon list), the (English) names of the chemical elements of the periodic table.\n\n\nThe list is to be in (ascending) order of the (chemical) element's atomic number:\n\n ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''\n\n... up to the last known (named) chemical element (at this time).\n\n\nDo not include any of the \"unnamed\" chemical element names such as:\n\n ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''\n\n\nTo make computer programming languages comparable, the statement widths should be\nrestricted to less than '''81''' bytes (characters), or less\nif a computer programming language has more restrictive limitations or standards.\n\nAlso mention what column the programming statements can start in if ''not'' \nin column one.\n\n\nThe list ''may'' have leading/embedded/trailing blanks during the\ndeclaration (the actual program statements), this is allow the list to be\nmore readable. The \"final\" list shouldn't have any leading/trailing or superfluous\nblanks (when stored in the program's \"memory\").\n\nThis list should be written with the idea in mind that the\nprogram ''will'' be updated, most likely someone other than the\noriginal author, as there will be newer (discovered) elements of the periodic\ntable being added (possibly in the near future). These future updates\nshould be one of the primary concerns in writing these programs and it should be \"easy\"\nfor someone else to add chemical elements to the list (within the computer\nprogram).\n\nAttention should be paid so as to not exceed the ''clause length'' of\ncontinued or specified statements, if there is such a restriction. If the\nlimit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.\n\n\n;Task:\n:* Write a computer program (by whatever name) to contain a list of the known elements.\n:* The program should eventually contain a long literal of words (the elements).\n:* The literal should show how one could create a long list of blank-delineated words.\n:* The \"final\" (stored) list should only have a single blank between elements.\n:* Try to use the most idiomatic approach(es) in creating the final list.\n:* Use continuation if possible, and/or show alternatives (possibly using concatenation).\n:* Use a program comment to explain what the continuation character is if it isn't obvious.\n:* The program should contain a variable that has the date of the last update/revision.\n:* The program, when run, should display with verbiage:\n:::* The last update/revision date (and should be unambiguous).\n:::* The number of chemical elements in the list.\n:::* The name of the highest (last) element name.\n\n\nShow all output here, on this page.\n\n\n\n", "solution": "elements = %w(\nhydrogen helium lithium beryllium\nboron carbon nitrogen oxygen\nfluorine neon sodium magnesium\naluminum silicon phosphorous sulfur\nchlorine argon potassium calcium\nscandium titanium vanadium chromium\nmanganese iron cobalt nickel\ncopper zinc gallium germanium\narsenic selenium bromine krypton\nrubidium strontium yttrium zirconium\nniobium molybdenum technetium ruthenium\nrhodium palladium silver cadmium\nindium tin antimony tellurium\niodine xenon cesium barium\nlanthanum cerium praseodymium neodymium\npromethium samarium europium gadolinium\nterbium dysprosium holmium erbium\nthulium ytterbium lutetium hafnium\ntantalum tungsten rhenium osmium\niridium platinum gold mercury\nthallium lead bismuth polonium\nastatine radon francium radium\nactinium thorium protactinium uranium\nneptunium plutonium americium curium\nberkelium californium einsteinium fermium\nmendelevium nobelium lawrencium rutherfordium\ndubnium seaborgium bohrium hassium\nmeitnerium darmstadtium roentgenium copernicium\nnihonium flerovium moscovium livermorium\ntennessine oganesson)\n\nputs \"Last mutation #{ File.mtime(__FILE__) }\nnumber of elements: #{elements.size}\nlast element: #{elements.last}\"\n"} {"title": "Long year", "language": "Ruby", "task": "Most years have 52 weeks, some have 53, according to ISO8601.\n\n\n;Task:\nWrite a function which determines if a given year is long (53 weeks) or not, and demonstrate it.\n\n", "solution": "require 'date'\n\ndef long_year?(year = Date.today.year)\n Date.new(year, 12, 28).cweek == 53\nend\n\n(2020..2030).each{|year| puts \"#{year} is long? #{ long_year?(year) }.\" } \n"} {"title": "Longest common subsequence", "language": "Ruby", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''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.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe 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''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA 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.\n\nA 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].\n\nEvery 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''.\n\nAccording 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.\n\n'''Background'''\n\nWhere 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.\n\nThe 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.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn 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.\n\nA 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'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn 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.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "===Recursion===\nThis solution is similar to the Haskell one. It is slow (The time complexity is exponential.)\n"} {"title": "Longest common subsequence", "language": "Ruby 1.9", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''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.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe 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''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA 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.\n\nA 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].\n\nEvery 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''.\n\nAccording 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.\n\n'''Background'''\n\nWhere 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.\n\nThe 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.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn 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.\n\nA 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'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn 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.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "class LCS\n SELF, LEFT, UP, DIAG = [0,0], [0,-1], [-1,0], [-1,-1]\n \n def initialize(a, b)\n @m = Array.new(a.length) { Array.new(b.length) }\n a.each_char.with_index do |x, i|\n b.each_char.with_index do |y, j|\n match(x, y, i, j)\n end\n end\n end\n \n def match(c, d, i, j)\n @i, @j = i, j\n @m[i][j] = compute_entry(c, d)\n end\n \n def lookup(x, y) [@i+x, @j+y] end\n def valid?(i=@i, j=@j) i >= 0 && j >= 0 end\n \n def peek(x, y)\n i, j = lookup(x, y)\n valid?(i, j) ? @m[i][j] : 0\n end \n \n def compute_entry(c, d)\n c == d ? peek(*DIAG) + 1 : [peek(*LEFT), peek(*UP)].max\n end\n \n def backtrack\n @i, @j = @m.length-1, @m[0].length-1\n y = []\n y << @i+1 if backstep? while valid?\n y.reverse\n end\n \n def backtrack2\n @i, @j = @m.length-1, @m[0].length-1\n y = []\n y << @j+1 if backstep? while valid?\n [backtrack, y.reverse]\n end\n \n def backstep?\n backstep = compute_backstep\n @i, @j = lookup(*backstep)\n backstep == DIAG\n end\n \n def compute_backstep\n case peek(*SELF)\n when peek(*LEFT) then LEFT\n when peek(*UP) then UP\n else DIAG\n end\n end\nend\n\ndef lcs(a, b)\n walker = LCS.new(a, b)\n walker.backtrack.map{|i| a[i]}.join\nend\n\nif $0 == __FILE__\n puts lcs('thisisatest', 'testing123testing')\n puts lcs(\"rosettacode\", \"raisethysword\")\nend"} {"title": "Longest common substring", "language": "Ruby from C#", "task": "Write a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote 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. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*Generalize Suffix Tree\n*[[Ukkonen's Suffix Tree Construction]]\n\n", "solution": "def longest_common_substring(a,b)\n lengths = Array.new(a.length){Array.new(b.length, 0)}\n greatestLength = 0\n output = \"\"\n a.each_char.with_index do |x,i|\n b.each_char.with_index do |y,j|\n next if x != y\n lengths[i][j] = (i.zero? || j.zero?) ? 1 : lengths[i-1][j-1] + 1\n if lengths[i][j] > greatestLength\n greatestLength = lengths[i][j]\n output = a[i - greatestLength + 1, greatestLength]\n end\n end\n end\n output\nend\n\np longest_common_substring(\"thisisatest\", \"testing123testing\")"} {"title": "Longest increasing subsequence", "language": "Ruby", "task": "Calculate and show here a longest increasing subsequence of the list:\n:\\{3, 2, 6, 4, 5, 1\\}\nAnd of the list:\n:\\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\\}\n\nNote that a list may have more than one subsequence that is of the maximum length.\n\n\n\n;Ref:\n# Dynamic Programming #1: Longest Increasing Subsequence on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "Node = Struct.new(:val, :back)\n\ndef lis(n)\n pileTops = []\n # sort into piles\n for x in n\n # binary search\n low, high = 0, pileTops.size-1\n while low <= high\n mid = low + (high - low) / 2\n if pileTops[mid].val >= x\n high = mid - 1\n else\n low = mid + 1\n end\n end\n i = low\n node = Node.new(x)\n node.back = pileTops[i-1] if i > 0\n pileTops[i] = node\n end\n \n result = []\n node = pileTops.last\n while node\n result.unshift(node.val)\n node = node.back\n end\n result\nend\n\np lis([3, 2, 6, 4, 5, 1])\np lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])"} {"title": "Lucky and even lucky numbers", "language": "Ruby from Python", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# 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 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* 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 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* 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 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* 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 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# 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 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* 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 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* 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 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* 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:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n +-------------------+----------------------------------------------------+\n | j | Jth lucky number |\n | j , lucky | Jth lucky number |\n | j , evenLucky | Jth even lucky number |\n | | |\n | j k | Jth through Kth (inclusive) lucky numbers |\n | j k lucky | Jth through Kth (inclusive) lucky numbers |\n | j k evenLucky | Jth through Kth (inclusive) even lucky numbers |\n | | |\n | j -k | all lucky numbers in the range j --> |k| |\n | j -k lucky | all lucky numbers in the range j --> |k| |\n | j -k evenLucky | all even lucky numbers in the range j --> |k| |\n +-------------------+----------------------------------------------------+\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki Lucky numbers.\n* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.\n* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.\n* Entry lucky numbers on The Eric Weisstein's World of Mathematics.\n", "solution": "def generator(even=false, nmax=1000000)\n start = even ? 2 : 1\n Enumerator.new do |y|\n n = 1\n ary = [0] + (start..nmax).step(2).to_a # adds [0] to revise the 0 beginnings.\n y << ary[n]\n while (m = ary[n+=1]) < ary.size\n y << m\n (m...ary.size).step(m){|i| ary[i]=nil}\n ary.compact! # remove nil\n end\n # drain\n ary[n..-1].each{|i| y << i}\n raise StopIteration\n end\nend\n\ndef lucky(argv)\n j, k = argv[0].to_i, argv[1].to_i\n mode = /even/i=~argv[2] ? :'even lucky' : :lucky\n seq = generator(mode == :'even lucky')\n ord = ->(n){\"#{n}#{(n%100).between?(11,19) ? 'th' : %w[th st nd rd th th th th th th][n%10]}\"}\n if k.zero?\n puts \"#{ord[j]} #{mode} number: #{seq.take(j).last}\"\n elsif 0 < k\n puts \"#{ord[j]} through #{ord[k]} (inclusive) #{mode} numbers\",\n \" #{seq.take(k)[j-1..-1]}\"\n else\n k = -k\n ary = []\n loop do\n case num=seq.next\n when 1...j\n when j..k then ary << num\n else break\n end\n end\n puts \"all #{mode} numbers in the range #{j}..#{k}\",\n \" #{ary}\"\n end\nend\n\nif __FILE__ == $0\n lucky(ARGV)\nend"} {"title": "Lychrel numbers", "language": "Ruby from Python", "task": "::# Take an integer n, greater than zero.\n::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n.\n::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.\n\n\nThe above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.\n\n\n;Example:\nIf n0 = 12 we get\n\n 12\n 12 + 21 = 33, a palindrome!\n\n\nAnd if n0 = 55 we get\n\n 55\n 55 + 55 = 110\n 110 + 011 = 121, a palindrome!\n\n\nNotice that the check for a palindrome happens ''after'' an addition.\n\n\nSome 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. \n\nThese numbers that do not end in a palindrome are called '''Lychrel numbers'''.\n\nFor the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.\n\n\n;Seed and related Lychrel numbers:\nAny integer produced in the sequence of a Lychrel number is also a Lychrel number.\n\nIn 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:\n\n 196\n 196 + 691 = 887\n 887 + 788 = 1675\n 1675 + 5761 = 7436\n 7436 + 6347 = 13783\n 13783 + 38731 = 52514\n 52514 + 41525 = 94039\n ...\n\n\n 689\n 689 + 986 = 1675\n 1675 + 5761 = 7436\n ...\n\nSo we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. \n\nBecause 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.\n\n\n;Task:\n* 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).\n* Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found.\n* Print any seed Lychrel or related number that is itself a palindrome.\n\n\nShow all output here.\n\n\n;References:\n* What's special about 196? Numberphile video.\n* A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).\n* Status of the 196 conjecture? Mathoverflow.\n\n", "solution": "require 'set'\n\ndef add_reverse(num, max_iter=1000)\n (1..max_iter).each_with_object(Set.new([num])) do |_,nums|\n num += reverse_int(num)\n nums << num\n return nums if palindrome?(num)\n end\nend\n\ndef palindrome?(num)\n num == reverse_int(num)\nend\n\ndef reverse_int(num)\n num.to_s.reverse.to_i\nend\n\ndef split_roots_from_relateds(roots_and_relateds)\n roots = roots_and_relateds.dup\n i = 1\n while i < roots.length\n this = roots[i]\n if roots[0...i].any?{|prev| this.intersect?(prev)}\n roots.delete_at(i)\n else\n i += 1\n end\n end\n root = roots.map{|each_set| each_set.min}\n related = roots_and_relateds.map{|each_set| each_set.min}\n related = related.reject{|n| root.include?(n)}\n return root, related\nend\n\ndef find_lychrel(maxn, max_reversions)\n series = (1..maxn).map{|n| add_reverse(n, max_reversions*2)}\n roots_and_relateds = series.select{|s| s.length > max_reversions}\n split_roots_from_relateds(roots_and_relateds)\nend\n\nmaxn, reversion_limit = 10000, 500\nputs \"Calculations using n = 1..#{maxn} and limiting each search to 2*#{reversion_limit} reverse-digits-and-adds\"\nlychrel, l_related = find_lychrel(maxn, reversion_limit)\nputs \" Number of Lychrel numbers: #{lychrel.length}\"\nputs \" Lychrel numbers: #{lychrel}\"\nputs \" Number of Lychrel related: #{l_related.length}\"\npals = (lychrel + l_related).select{|x| palindrome?(x)}.sort\nputs \" Number of Lychrel palindromes: #{pals.length}\"\nputs \" Lychrel palindromes: #{pals}\""} {"title": "MAC vendor lookup", "language": "Ruby", "task": "Every connected device around the world comes with a unique Media Access Control address, or a MAC address. \n\nA common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.\n\n\n;Task:\nInterface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.\n\nA 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.\n\nMany 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.\n\n'''{\"errors\":{\"detail\":\"Too Many Requests\",\"message\":\"Please slow down your requests or upgrade your plan at https://macvendors.com\"}}'''\n\n", "solution": "require 'net/http'\n\narr = ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21', 'D4:F4:6F:C9:EF:8D', '23:45:67']\n\narr.each do |addr|\n vendor = Net::HTTP.get('api.macvendors.com', \"/#{addr}/\") rescue nil\n puts \"#{addr} #{vendor}\" \nend"} {"title": "Mad Libs", "language": "Ruby", "task": "{{wikipedia}}\n\n\nMad 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. \n\n\n;Task;\nWrite a program to create a Mad Libs like story. \n\nThe program should read an arbitrary multiline story from input.\n\nThe story will be terminated with a blank line. \n\nThen, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.\n\nStop when there are none left and print the final story.\n\n\nThe input should be an arbitrary story in the form:\n\n went for a walk in the park. \nfound a . decided to take it home.\n\nGiven this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).\n\n\n\n", "solution": "puts \"Enter a story, terminated by an empty line:\"\nstory = \"\"\nuntil (line = gets).chomp.empty?\n story << line\nend\n\nstory.scan(/(?<=[<]).+?(?=[>])/).uniq.each do |var|\n print \"Enter a value for '#{var}': \"\n story.gsub!(/<#{var}>/, gets.chomp)\nend\n\nputs\nputs story"} {"title": "Magic 8-ball", "language": "Ruby", "task": "Create Magic 8-Ball. \n\n\nSee details at: Magic 8-Ball.\n\n\n\n", "solution": "#!/usr/bin/ruby\n\nclass EightBall\n def initialize\n print \"Welcome to 8 ball! Ask your question below. \"\n puts \"Type 'quit' to exit the program.\\n\\n\"\n @responses = [\"It is certain\", \"It is decidedly so\",\n \"Without a doubt\", \"Yes, definitely\",\n \"You may rely on it\", \"As I see it, yes\",\n \"Most likely\", \"Outlook good\",\n \"Signs point to yes\", \"Yes\",\n \"Reply hazy, try again\", \"Ask again later\",\n \"Better not tell you now\",\n \"Cannot predict now\",\n \"Concentrate and ask again\", \"Don't bet on it\",\n \"My reply is no\", \"My sources say no\",\n \"Outlook not so good\", \"Very doubtful\"]\n end\n\n def ask_question\n print \"Question: \"\n question = gets\n\n if question.chomp.eql? \"quit\"\n exit(0)\n end\n\n puts \"Response: #{@responses.sample} \\n\\n\"\n end\n\n def run\n loop do\n ask_question\n end\n end\nend\n\neight_ball = EightBall.new\neight_ball.run\n"} {"title": "Magic squares of doubly even order", "language": "Ruby", "task": "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''). \n\nA magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). \n\nThis means that the subsquares also have an even size, which plays a role in the construction.\n\n \n{| 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%\"\n|-\n|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''\n|-\n|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''\n|-\n|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''\n|-\n|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''\n|-\n|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''\n|-\n|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''\n|-\n|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''\n|-\n|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''\n|}\n\n;Task\nCreate a magic square of '''8 x 8'''.\n\n\n;Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n\n\n;See also:\n* Doubly Even Magic Squares (1728.org)\n\n", "solution": "def double_even_magic_square(n)\n raise ArgumentError, \"Need multiple of four\" if n%4 > 0\n block_size, max = n/4, n*n\n pre_pat = [true, false, false, true,\n false, true, true, false]\n pre_pat += pre_pat.reverse\n pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size\n flat_ar = pattern.each_with_index.map{|yes, num| yes ? num+1 : max-num}\n flat_ar.each_slice(n).to_a\nend\n\ndef to_string(square)\n n = square.size\n fmt = \"%#{(n*n).to_s.size + 1}d\" * n\n square.inject(\"\"){|str,row| str << fmt % row << \"\\n\"}\nend\n\nputs to_string(double_even_magic_square(8))"} {"title": "Magic squares of odd order", "language": "Ruby", "task": "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''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| 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%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "def odd_magic_square(n)\n raise ArgumentError \"Need odd positive number\" if n.even? || n <= 0\n n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }\nend\n\n[3, 5, 9].each do |n|\n puts \"\\nSize #{n}, magic sum #{(n*n+1)/2*n}\"\n fmt = \"%#{(n*n).to_s.size + 1}d\" * n\n odd_magic_square(n).each{|row| puts fmt % row}\nend\n"} {"title": "Magic squares of singly even order", "language": "Ruby", "task": "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''). \n\nA 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.\n\n;Task\nCreate a magic square of 6 x 6.\n\n\n; Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of doubly even order]]\n\n; See also\n* Singly Even Magic Squares (1728.org)\n\n", "solution": "def odd_magic_square(n)\n n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }\nend\n\ndef single_even_magic_square(n) \n raise ArgumentError, \"must be even, but not divisible by 4.\" unless (n-2) % 4 == 0\n raise ArgumentError, \"2x2 magic square not possible.\" if n == 2\n\n order = (n-2)/4\n odd_square = odd_magic_square(n/2)\n to_add = (0..3).map{|f| f*n*n/4}\n quarts = to_add.map{|f| odd_square.dup.map{|row|row.map{|el| el+f}} }\n\n sq = []\n quarts[0].zip(quarts[2]){|d1,d2| sq << [d1,d2].flatten}\n quarts[3].zip(quarts[1]){|d1,d2| sq << [d1,d2].flatten}\n\n sq = sq.transpose\n order.times{|i| sq[i].rotate!(n/2)}\n swap(sq[0][order], sq[0][-order-1])\n swap(sq[order][order], sq[order][-order-1])\n (order-1).times{|i| sq[-(i+1)].rotate!(n/2)}\n randomize(sq)\nend\n\ndef swap(a,b)\n a,b = b,a\nend\n\ndef randomize(square)\n square.shuffle.transpose.shuffle\nend\n\ndef to_string(square)\n n = square.size\n fmt = \"%#{(n*n).to_s.size + 1}d\" * n\n square.inject(\"\"){|str,row| str << fmt % row << \"\\n\"}\nend\n\nputs to_string(single_even_magic_square(6))"} {"title": "Map range", "language": "Ruby", "task": "Given two ranges: \n:::* [a_1,a_2] and \n:::* [b_1,b_2]; \n:::* then a value s in range [a_1,a_2]\n:::* is linearly mapped to a value t in range [b_1,b_2]\n where: \n\n\n:::* t = b_1 + {(s - a_1)(b_2 - b_1) \\over (a_2 - a_1)}\n\n\n;Task:\nWrite 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. \n\nUse this function to map values from the range [0, 10] to the range [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "def map_range(a, b, s)\n af, al, bf, bl = a.first, a.last, b.first, b.last\n bf + (s - af)*(bl - bf).quo(al - af)\nend\n\n(0..10).each{|s| puts \"%s maps to %g\" % [s, map_range(0..10, -1..0, s)]}"} {"title": "Maximum triangle path sum", "language": "Ruby", "task": "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:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour 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.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "triangle = \n\" 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\"\n\nar = triangle.each_line.map{|line| line.split.map(&:to_i)}\nputs ar.inject([]){|res,x|\n maxes = [0, *res, 0].each_cons(2).map(&:max)\n x.zip(maxes).map{|a,b| a+b}\n}.max\n# => 1320"} {"title": "McNuggets problem", "language": "Ruby from Go", "task": "From Wikipedia:\n The McNuggets version of the coin problem was introduced by Henri Picciotto,\n who included it in his algebra textbook co-authored with Anita Wah. Picciotto\n thought of the application in the 1980s while dining with his son at\n McDonald's, working the problem out on a napkin. A McNugget number is\n the total number of McDonald's Chicken McNuggets in any number of boxes.\n In the United Kingdom, the original boxes (prior to the introduction of\n the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.\n\n;Task:\nCalculate (from 0 up to a limit of 100) the largest non-McNuggets\nnumber (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''\nwhere ''x'', ''y'' and ''z'' are natural numbers).\n\n", "solution": "def mcnugget(limit)\n sv = (0..limit).to_a\n\n (0..limit).step(6) do |s|\n (0..limit).step(9) do |n|\n (0..limit).step(20) do |t|\n sv.delete(s + n + t)\n end\n end\n end\n\n sv.max\nend\n\nputs(mcnugget 100)"} {"title": "Memory layout of a data structure", "language": "Ruby", "task": "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.\n Pin Settings for Plug\n (Reverse order for socket.)\n __________________________________________\n 1 2 3 4 5 6 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20 21 22 23 24 25\n _________________\n 1 2 3 4 5\n 6 7 8 9\n 25 pin 9 pin\n 1 - PG Protective ground\n 2 - TD Transmitted data 3\n 3 - RD Received data 2\n 4 - RTS Request to send 7\n 5 - CTS Clear to send 8\n 6 - DSR Data set ready 6\n 7 - SG Signal ground 5\n 8 - CD Carrier detect 1\n 9 - + voltage (testing)\n 10 - - voltage (testing)\n 11 -\n 12 - SCD Secondary CD\n 13 - SCS Secondary CTS\n 14 - STD Secondary TD\n 15 - TC Transmit clock\n 16 - SRD Secondary RD\n 17 - RC Receiver clock\n 18 -\n 19 - SRS Secondary RTS \n 20 - DTR Data terminal ready 4\n 21 - SQD Signal quality detector\n 22 - RI Ring indicator 9\n 23 - DRS Data rate select\n 24 - XTC External clock\n 25 -\n", "solution": "require 'bit-struct'\n\nclass RS232_9 < BitStruct\n unsigned :cd, 1, \"Carrier detect\" #1\n unsigned :rd, 1, \"Received data\" #2\n unsigned :td, 1, \"Transmitted data\" #3\n unsigned :dtr, 1, \"Data terminal ready\" #4\n unsigned :sg, 1, \"Signal ground\" #5\n unsigned :dsr, 1, \"Data set ready\" #6\n unsigned :rts, 1, \"Request to send\" #7\n unsigned :cts, 1, \"Clear to send\" #8\n unsigned :ri, 1, \"Ring indicator\" #9\n \n def self.new_with_int(value)\n data = {}\n fields.each_with_index {|f, i| data[f.name] = value[i]}\n new(data)\n end\nend\n\nnum = rand(2**9 - 1)\nputs \"num = #{num}\"\n\nsample1 = RS232_9.new([(\"%09d\" % num.to_s(2)).reverse].pack(\"B*\"))\nputs sample1.inspect_detailed\n\nsample2 = RS232_9.new_with_int(num)\nputs sample2.inspect_detailed\n\nputs \"CD is #{sample2.cd == 1 ? 'on' : 'off'}\""} {"title": "Metallic ratios", "language": "Ruby 2.3", "task": "Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series\nof related ratios that are referred to as the \"'''Metallic ratios'''\".\n\nThe '''Golden ratio''' was discovered and named by ancient civilizations as it was\nthought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was\nalso known to the early Greeks, though was not named so until later as a nod to\nthe '''Golden ratio''' to which it is closely related. The series has been extended to\nencompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means'').\n''Somewhat incongruously as the original Golden ratio referred to the adjective \"golden\" rather than the metal \"gold\".''\n\n'''Metallic ratios''' are the real roots of the general form equation:\n\n x2 - bx - 1 = 0 \n\nwhere the integer '''b''' determines which specific one it is.\n\nUsing the quadratic equation:\n\n ( -b +- (b2 - 4ac) ) / 2a = x \n\nSubstitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get:\n\n ( b +- (b2 + 4) ) ) / 2 = x \n\nWe only want the real root:\n\n ( b + (b2 + 4) ) ) / 2 = x \n\nWhen we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''.\n\n ( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989... \n\nWith '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''.\n\n ( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562... \n\nWhen the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5'''\nare sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as\nstandard. After that there isn't really any attempt at standardized names. They\nare given names here on this page, but consider the names fanciful rather than\ncanonical.\n\nNote that technically, '''b''' can be '''0''' for a \"smaller\" ratio than the '''Golden ratio'''.\nWe will refer to it here as the '''Platinum ratio''', though it is kind-of a\ndegenerate case.\n\n'''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions:\n\n [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] \n\n\nSo, The first ten '''Metallic ratios''' are:\n\n:::::: {| class=\"wikitable\" style=\"text-align: center;\"\n|+ Metallic ratios\n!Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link\n|-\n|Platinum||0||(0 + 4) / 2|| 1||-||-\n|-\n|Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]]\n|-\n|Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]]\n|-\n|Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]]\n|-\n|Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]]\n|-\n|Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]]\n|-\n|Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]]\n|-\n|Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]]\n|-\n|Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]]\n|-\n|Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]]\n|}\n\n\n\n\nThere are other ways to find the '''Metallic ratios'''; one, (the focus of this task)\nis through '''successive approximations of Lucas sequences'''.\n\nA traditional '''Lucas sequence''' is of the form:\n\n x''n'' = P * x''n-1'' - Q * x''n-2''\n\nand starts with the first 2 values '''0, 1'''. \n\nFor our purposes in this task, to find the metallic ratios we'll use the form:\n\n x''n'' = b * x''n-1'' + x''n-2''\n\n( '''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.'' \n\nAt any rate, when '''b = 1''' we get:\n\n x''n'' = x''n-1'' + x''n-2''\n\n 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...\n\nmore commonly known as the Fibonacci sequence.\n\nWhen '''b = 2''':\n\n x''n'' = 2 * x''n-1'' + x''n-2''\n\n 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...\n\n\nAnd so on.\n\n\nTo find the ratio by successive approximations, divide the ('''n+1''')th term by the\n'''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio.\n\nFor '''b = 1''' (Fibonacci sequence):\n\n 1/1 = 1\n 2/1 = 2\n 3/2 = 1.5\n 5/3 = 1.666667\n 8/5 = 1.6\n 13/8 = 1.625\n 21/13 = 1.615385\n 34/21 = 1.619048\n 55/34 = 1.617647\n 89/55 = 1.618182\n etc.\n\nIt converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest\npossible convergence for any irrational number.\n\n\n;Task\n\nFor each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''':\n\n* Generate the corresponding \"Lucas\" sequence.\n* Show here, on this page, at least the first '''15''' elements of the \"Lucas\" sequence.\n* Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places.\n* Show the '''value''' of the '''approximation''' at the required accuracy.\n* Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?).\n\nOptional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places.\n\nYou may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.\n\n;See also\n* Wikipedia: Metallic mean\n* Wikipedia: Lucas sequence\n\n", "solution": "require('bigdecimal')\nrequire('bigdecimal/util')\n\n# An iterator over the Lucas Sequence for 'b'.\n# (The special case of: x(n) = b * x(n-1) + x(n-2).)\n\ndef lucas(b)\n Enumerator.new do |yielder|\n xn2 = 1 ; yielder.yield(xn2)\n xn1 = 1 ; yielder.yield(xn1)\n loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(xn1) }\n end\nend\n\n# Compute the Metallic Ratio to 'precision' from the Lucas Sequence for 'b'.\n# (Uses the lucas(b) iterator, above.)\n# The metallic ratio is approximated by x(n) / x(n-1).\n# Returns a struct of the approximate metallic ratio (.ratio) and the\n# number of terms required to achieve the given precision (.terms).\n\ndef metallic_ratio(b, precision)\n xn2 = xn1 = prev = this = 0\n lucas(b).each.with_index do |xn, inx|\n case inx\n when 0\n xn2 = BigDecimal(xn)\n when 1\n xn1 = BigDecimal(xn)\n prev = xn1.div(xn2, 2 * precision).round(precision)\n else\n xn2, xn1 = xn1, BigDecimal(xn)\n this = xn1.div(xn2, 2 * precision).round(precision)\n return Struct.new(:ratio, :terms).new(prev, inx - 1) if prev == this\n prev = this\n end\n end\nend\n\nNAMES = [ 'Platinum', 'Golden', 'Silver', 'Bronze', 'Copper',\n 'Nickel', 'Aluminum', 'Iron', 'Tin', 'Lead' ]\n\nputs\nputs('Lucas Sequences...')\nputs('%1s %s' % ['b', 'sequence'])\n(0..9).each do |b|\n puts('%1d %s' % [b, lucas(b).first(15)])\nend\n\nputs\nputs('Metallic Ratios to 32 places...')\nputs('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio'])\n(0..9).each do |b|\n rn = metallic_ratio(b, 32)\n puts('%-9s %1d %3d %s' % [NAMES[b], b, rn.terms, rn.ratio.to_s('F')])\nend\n\nputs\nputs('Golden Ratio to 256 places...')\nputs('%-9s %1s %3s %s' % ['name', 'b', 'n', 'ratio'])\ngold_rn = metallic_ratio(1, 256)\nputs('%-9s %1d %3d %s' % [NAMES[1], 1, gold_rn.terms, gold_rn.ratio.to_s('F')])"} {"title": "Metaprogramming", "language": "Ruby", "task": "{{omit from|BBC BASIC}}\nName 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. \n\nFor 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.\n\n", "solution": "class IDVictim\n \n # Create elements of this man, woman, or child's identification.\n attr_accessor :name, :birthday, :gender, :hometown\n \n # Allows you to put in a space for anything which is not covered by the\n # preexisting elements.\n def self.new_element(element)\n attr_accessor element\n end\n \nend"} {"title": "Metronome", "language": "Ruby", "task": "The task is to implement a metronome. \n\nThe 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.\n\nFor 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. \n\nHowever, the playing of the sounds should not interfere with the timing of the metronome.\n\nThe 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. \n\nIf the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.\n\n", "solution": "#!/usr/bin/ruby\n\nbpm = Integer(ARGV[0]) rescue 60 # sets BPM by the first command line argument, set to 60 if none provided\nmsr = Integer(ARGV[1]) rescue 4 # sets number of beats in a measure by the second command line argument, set to 4 if none provided\ni = 0\n\nloop do\n (msr-1).times do \n puts \"\\a\"\n sleep(60.0/bpm)\n end\n puts \"\\aAND #{i += 1}\"\n sleep(60.0/bpm)\nend\n"} {"title": "Mian-Chowla sequence", "language": "Ruby from Go", "task": "The Mian-Chowla sequence is an integer sequence defined recursively.\n\n\nMian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "require 'set'\nn, ts, mc, sums = 100, [], [1], Set.new\nsums << 2\nst = Time.now\nfor i in (1 .. (n-1))\n for j in mc[i-1]+1 .. Float::INFINITY\n mc[i] = j\n for k in (0 .. i)\n if (sums.include?(sum = mc[k]+j))\n ts.clear\n break \n end\n ts << sum\n end\n if (ts.length > 0)\n sums = sums | ts\n break\n end\n end\nend\net = (Time.now - st) * 1000\ns = \" of the Mian-Chowla sequence are:\\n\"\nputs \"The first 30 terms#{s}#{mc.slice(0..29).join(' ')}\\n\\n\"\nputs \"Terms 91 to 100#{s}#{mc.slice(90..99).join(' ')}\\n\\n\"\nputs \"Computation time was #{et.round(1)}ms.\""} {"title": "Middle three digits", "language": "Ruby", "task": "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.\n\nNote: The order of the middle digits should be preserved.\n\nYour 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:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "def middle_three_digits(num)\n # minus sign doesn't factor into digit count,\n # and calling #abs acts as a duck-type assertion\n num = num.abs\n \n # convert to string and find length\n length = (str = num.to_s).length\n \n # check validity\n raise ArgumentError, \"Number must have at least three digits\" if length < 3\n raise ArgumentError, \"Number must have an odd number of digits\" if length.even?\n \n return str[length/2 - 1, 3].to_i\nend"} {"title": "Mind boggling card trick", "language": "Ruby", "task": "Matt Parker of the \"Stand Up Maths channel\" has a YouTube video of a card trick that creates a semblance of order from chaos.\n\nThe task is to simulate the trick in a way that mimics the steps shown in the video.\n\n; 1. Cards.\n# Create a common deck of cards of 52 cards (which are half red, half black).\n# Give the pack a good shuffle.\n; 2. Deal from the shuffled deck, you'll be creating three piles.\n# Assemble the cards face down.\n## Turn up the ''top card'' and hold it in your hand. \n### if the card is black, then add the ''next'' card (unseen) to the \"black\" pile. \n### If the card is red, then add the ''next'' card (unseen) to the \"red\" pile.\n## 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).\n# Repeat the above for the rest of the shuffled deck.\n; 3. Choose a random number (call it '''X''') that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose '''X''' cards from the \"red\" pile (unseen), let's call this the \"red\" bunch. \n# Randomly choose '''X''' cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \"red\" bunch into the \"black\" pile.\n# Put the \"black\" bunch into the \"red\" pile.\n# (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).\n; 4. Order from randomness?\n# Verify (or not) the mathematician's assertion that: \n '''The number of black cards in the \"black\" pile equals the number of red cards in the \"red\" pile.''' \n\n\n(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)\n\nShow output on this page.\n\n", "solution": "deck = ([:black, :red] * 26 ).shuffle\nblack_pile, red_pile, discard = [], [], []\n\nuntil deck.empty? do\n discard << deck.pop\n discard.last == :black ? black_pile << deck.pop : red_pile << deck.pop\nend\n\nx = rand( [black_pile.size, red_pile.size].min )\n\nred_bunch = x.times.map{ red_pile.delete_at( rand( red_pile.size )) }\nblack_bunch = x.times.map{ black_pile.delete_at( rand( black_pile.size )) }\n\nblack_pile += red_bunch\nred_pile += black_bunch\n\nputs \"The magician predicts there will be #{black_pile.count( :black )} red cards in the other pile.\nDrumroll...\nThere were #{red_pile.count( :red )}!\"\n"} {"title": "Minimum multiple of m where digital sum equals m", "language": "Ruby", "task": "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'''.\n\n\n;Task\n\n* Find the first 40 elements of the sequence.\n\n\n\n;Stretch\n\n* Find the next 30 elements of the sequence.\n\n\n;See also\n\n;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n\n\n\n\n\n", "solution": "a131382 = (0..).lazy.map{|n| (1..).detect{|m|(n*m).digits.sum == n} }\na131382.take(70).each_slice(10){|slice| puts \"%8d\"*slice.size % slice }"} {"title": "Minimum positive multiple in base 10 using only 0 and 1", "language": "Ruby from Kotlin", "task": "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.\n\nThis is simple to do, but can be challenging to do efficiently.\n\nTo 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'''\".\n\n;Task:\n\nWrite a routine to find the B10 of a given integer. \n\nE.G. \n \n '''n''' '''B10''' '''n''' x '''multiplier'''\n 1 1 ( 1 x 1 )\n 2 10 ( 2 x 5 )\n 7 1001 ( 7 x 143 )\n 9 111111111 ( 9 x 12345679 )\n 10 10 ( 10 x 1 )\n\nand so on.\n\nUse the routine to find and display here, on this page, the '''B10''' value for: \n\n 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999\n\nOptionally find '''B10''' for:\n\n 1998, 2079, 2251, 2277\n\nStretch goal; find '''B10''' for:\n\n 2439, 2997, 4878\n\nThere 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.\n\n\n;See also:\n\n:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.\n:* How to find Minimum Positive Multiple in base 10 using only 0 and 1\n\n", "solution": "def mod(m, n)\n result = m % n\n if result < 0 then\n result = result + n\n end\n return result\nend\n\ndef getA004290(n)\n if n == 1 then\n return 1\n end\n arr = Array.new(n) { Array.new(n, 0) }\n arr[0][0] = 1\n arr[0][1] = 1\n m = 0\n while true\n m = m + 1\n if arr[m - 1][mod(-10 ** m, n)] == 1 then\n break\n end\n arr[m][0] = 1\n for k in 1 .. n - 1\n arr[m][k] = [arr[m - 1][k], arr[m - 1][mod(k - 10 ** m, n)]].max\n end\n end\n r = 10 ** m\n k = mod(-r, n)\n (m - 1).downto(1) { |j|\n if arr[j - 1][k] == 0 then\n r = r + 10 ** j\n k = mod(k - 10 ** j, n)\n end\n }\n if k == 1 then\n r = r + 1\n end\n return r\nend\n\ntestCases = Array(1 .. 10)\ntestCases.concat(Array(95 .. 105))\ntestCases.concat([297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878])\nfor n in testCases\n result = getA004290(n)\n print \"A004290(%d) = %d = %d * %d\\n\" % [n, result, n, result / n]\nend"} {"title": "Modified random distribution", "language": "Ruby", "task": "Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)\ntaking 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:\nwhile True:\n random1 = rgen()\n random2 = rgen()\n if random2 < modifier(random1):\n answer = random1\n break\n endif\nendwhile\n\n;Task:\n* Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:\n modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5) \n* Create a generator of random numbers with probabilities modified by the above function.\n* Generate >= 10,000 random numbers subject to the probability modification.\n* Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.\n\n\nShow your output here, on this page.\n\n", "solution": "def modifier(x) = (x - 0.5).abs * 2\n\ndef mod_rand\n loop do\n random1, random2 = rand, rand\n return random1 if random2 < modifier(random1)\n end\nend\n\nbins = 15\nbin_size = 1.0/bins\nh = {}\n(0...bins).each{|b| h[b*bin_size] = 0}\n\ntally = 50_000.times.map{ (mod_rand).div(bin_size) * bin_size}.tally(h)\nm = tally.values.max/40\ntally.each {|k,v| puts \"%f...%f %s %d\" % [k, k+bin_size, \"*\"*(v/m) , v] }\n"} {"title": "Modular arithmetic", "language": "Ruby", "task": "equivalence relation called ''congruence''. \n\nFor any positive integer p called the ''congruence modulus'', \ntwo numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:\n:a = b + k\\,p\n\nThe corresponding set of multiplicative inverse for this task.\n\nAddition 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.\n\nThe purpose of this task is to show, if your programming language allows it, \nhow to redefine operators so that they can be used transparently on modular integers. \nYou can do it either by using a dedicated library, or by implementing your own class.\n\nYou will use the following function for demonstration:\n:f(x) = x^{100} + x + 1\nYou will use 13 as the congruence modulus and you will compute f(10).\n\nIt 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. \nIn other words, the function is an algebraic expression that could be used with any ring, not just integers.\n\n", "solution": "# stripped version of Andrea Fazzi's submission to Ruby Quiz #179\n\nclass Modulo\n include Comparable\n\n def initialize(n = 0, m = 13)\n @n, @m = n % m, m\n end\n\n def to_i\n @n\n end\n \n def <=>(other_n)\n @n <=> other_n.to_i\n end\n\n [:+, :-, :*, :**].each do |meth|\n define_method(meth) { |other_n| Modulo.new(@n.send(meth, other_n.to_i), @m) }\n end\n\n def coerce(numeric)\n [numeric, @n]\n end\n\nend\n\n# Demo\nx, y = Modulo.new(10), Modulo.new(20)\n\np x > y # true\np x == y # false\np [x,y].sort #[#, #]\np x + y ##\np 2 + y # 9\np y + 2 ##\n\np x**100 + x +1 ##\n"} {"title": "Modular exponentiation", "language": "Ruby", "task": "Find the last '''40''' decimal digits of a^b, where\n\n::* a = 2988348162058574136915891421498819466320163312926952423791023078876139\n::* b = 2351399303373464486466122544523690094744975233415544072992656881240319\n\n\nA computer is too slow to find the entire value of a^b. \n\nInstead, the program must use a fast algorithm for modular exponentiation: a^b \\mod m.\n\nThe algorithm must work for any integers a, b, m, where b \\ge 0 and m > 0.\n\n", "solution": "a = 2988348162058574136915891421498819466320163312926952423791023078876139\nb = 2351399303373464486466122544523690094744975233415544072992656881240319\nm = 10**40\nputs a.pow(b, m)"} {"title": "Modular inverse", "language": "Ruby", "task": "From Wikipedia:\n\nIn modulo ''m'' is an integer ''x'' such that\n\n::a\\,x \\equiv 1 \\pmod{m}.\n\nOr in other words, such that:\n\n::\\exists k \\in\\Z,\\qquad a\\, x = 1 + k\\,m\n\nIt 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.\n\n\n;Task:\nEither by implementing the algorithm, by using a dedicated library or by using a built-in function in \nyour language, compute the modular inverse of 42 modulo 2017.\n\n", "solution": "#based on pseudo code from http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2 and from translating the python implementation.\ndef extended_gcd(a, b)\n last_remainder, remainder = a.abs, b.abs\n x, last_x, y, last_y = 0, 1, 1, 0\n while remainder != 0\n last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)\n x, last_x = last_x - quotient*x, x\n y, last_y = last_y - quotient*y, y\n end\n\n return last_remainder, last_x * (a < 0 ? -1 : 1)\nend\n\ndef invmod(e, et)\n g, x = extended_gcd(e, et)\n if g != 1\n raise 'The maths are broken!'\n end\n x % et\nend"} {"title": "Monads/List monad", "language": "Ruby", "task": "A Monad is a combination of a data-type with two helper functions written for that type. \n\nThe 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.\n\nThe 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.\n\nA sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. \n\nThe 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.\n\n\nDemonstrate in your programming language the following:\n\n#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)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String\n#Compose the two functions with bind\n\n", "solution": "class Array\n def bind(f)\n flat_map(&f)\n end\n def self.unit(*args)\n args\n end\n # implementing lift is optional, but is a great helper method for turning\n # ordinary funcitons into monadic versions of them.\n def self.lift(f)\n -> e { self.unit(f[e]) }\n end\nend\n\ninc = -> n { n + 1 }\nstr = -> n { n.to_s }\nlisty_inc = Array.lift(inc)\nlisty_str = Array.lift(str)\n\nArray.unit(3,4,5).bind(listy_inc).bind(listy_str) #=> [\"4\", \"5\", \"6\"]\n\n# Note that listy_inc and listy_str cannot be composed directly,\n# as they don't have compatible type signature.\n# Due to duck typing (Ruby will happily turn arrays into strings),\n# in order to show this, a new function will have to be used:\n\ndoub = -> n { 2*n }\nlisty_doub = Array.lift(doub)\n[3,4,5].bind(listy_inc).bind(listy_doub) #=> [8, 10, 12]\n\n# Direct composition will cause a TypeError, as Ruby cannot evaluate 2*[4, 5, 6]\n# Using bind with the composition is *supposed* to fail, no matter the programming language.\ncomp = -> f, g {-> x {f[g[x]]}}\n[3,4,5].bind(comp[listy_doub, listy_inc]) #=> TypeError: Array can't be coerced into Fixnum\n\n# Composition needs to be defined in terms of bind\nclass Array\n def bind_comp(f, g)\n bind(g).bind(f)\n end\nend\n\n[3,4,5].bind_comp(listy_doub, listy_inc) #=> [8, 10, 12]\n"} {"title": "Monads/Maybe monad", "language": "Ruby", "task": "Demonstrate in your programming language the following:\n\n#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)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String\n#Compose the two functions with bind\n\n\nA 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.\n\nA Maybe Monad is a monad which specifically encapsulates the type of an undefined value.\n\n", "solution": "class Maybe\n def initialize(value)\n @value = value\n end\n\n def map\n if @value.nil?\n self\n else\n Maybe.new(yield @value)\n end\n end\nend\n\nMaybe.new(3).map { |n| 2*n }.map { |n| n+1 }\n#=> #\n\nMaybe.new(nil).map { |n| 2*n }.map { |n| n+1 }\n#=> #\n\nMaybe.new(3).map { |n| nil }.map { |n| n+1 }\n#=> #\n\n# alias Maybe#new and write bind to be in line with task\n\nclass Maybe\n class << self\n alias :unit :new\n end\n \n def initialize(value)\n @value = value\n end\n\n def bind\n if @value.nil?\n self\n else\n yield @value\n end\n end\nend\n\nMaybe.unit(3).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) }\n#=> #\n\nMaybe.unit(nil).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) }\n#=> #\n"} {"title": "Monads/Writer monad", "language": "Ruby", "task": "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.\n\nDemonstrate in your programming language the following:\n\n# 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)\n# Write three simple functions: root, addOne, and half\n# Derive Writer monad versions of each of these functions\n# 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.)\n\n", "solution": "# 20220720 Ruby programming solution\nclass Writer\n attr_reader :value, :log\n\n def initialize(value, log = \"New\")\n @value = value\n if value.is_a? Proc\n @log = log\n else\n @log = log + \": \" + @value.to_s \n end\n end\n\n def self.unit(value, log)\n Writer.new(value, log)\n end\n\n def bind(mwriter)\n new_value = mwriter.value.call(@value)\n new_log = @log + \"\\n\" + mwriter.log\n self.class.new(new_value, new_log)\n end\nend\n\nlam_sqrt = ->(number) { Math.sqrt(number) }\nlam_add_one = ->(number) { number + 1 }\nlam_half = ->(number) { number / 2.0 }\n\nsqrt = Writer.unit( lam_sqrt, \"Took square root\")\nadd_one = Writer.unit( lam_add_one, \"Added one\")\nhalf = Writer.unit( lam_half, \"Divided by 2\")\n\nm1 = Writer.unit(5, \"Initial value\")\nm2 = m1.bind(sqrt).bind(add_one).bind(half)\n\nputs \"The final value is #{m2.value}\\n\\n\"\nputs \"This value was derived as follows:\"\nputs m2.log\n"} {"title": "Move-to-front algorithm", "language": "Ruby", "task": "Given a symbol table of a ''zero-indexed'' array of all possible input symbols\nthis algorithm reversibly transforms a sequence\nof input symbols into an array of output numbers (indices).\n\nThe transform in many cases acts to give frequently repeated input symbols\nlower indices which is useful in some compression algorithms.\n\n\n;Encoding algorithm:\n\n for each symbol of the input sequence:\n output the index of the symbol in the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Decoding algorithm:\n\n # Using the same starting symbol table\n for each index of the input sequence:\n output the symbol at that index of the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Example:\nEncoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''\n\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''b'''roood\n| 1\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| b'''r'''oood\n| 1 17\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| br'''o'''ood\n| 1 17 15\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| bro'''o'''od\n| 1 17 15 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| broo'''o'''d\n| 1 17 15 0 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| brooo'''d'''\n| 1 17 15 0 0 5\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\nDecoding the indices back to the original symbol order:\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''1''' 17 15 0 0 5\n| b\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| 1 '''17''' 15 0 0 5\n| br\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| 1 17 '''15''' 0 0 5\n| bro\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| 1 17 15 '''0''' 0 5\n| broo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 '''0''' 5\n| brooo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 0 '''5''' \n| broood\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\n;Task:\n:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. \n:* Show the strings and their encoding here.\n:* Add a check to ensure that the decoded string is the same as the original.\n\n\nThe strings are: \n\n broood \n bananaaa \n hiphophiphop \n(Note the misspellings in the above strings.)\n\n", "solution": "module MoveToFront\n \n ABC = (\"a\"..\"z\").to_a.freeze\n \n def self.encode(str)\n ar = ABC.dup\n str.chars.each_with_object([]) do |char, memo|\n memo << (i = ar.index(char))\n ar = m2f(ar,i)\n end\n end\n \n def self.decode(indices)\n ar = ABC.dup\n indices.each_with_object(\"\") do |i, str|\n str << ar[i]\n ar = m2f(ar,i)\n end\n end\n \n private\n def self.m2f(ar,i)\n [ar.delete_at(i)] + ar\n end\n \nend\n\n['broood', 'bananaaa', 'hiphophiphop'].each do |word|\n p word == MoveToFront.decode(p MoveToFront.encode(p word))\nend"} {"title": "Multifactorial", "language": "Ruby", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\nMultifactorials generalize factorials as follows:\n: n! = n(n-1)(n-2)...(2)(1)\n: n!! = n(n-2)(n-4)...\n: n!! ! = n(n-3)(n-6)...\n: n!! !! = n(n-4)(n-8)...\n: n!! !! ! = n(n-5)(n-10)...\n\nIn all cases, the terms in the products are positive integers.\n\nIf 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: \n# Write a function that given n and the degree, calculates the multifactorial.\n# 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.\n\n\n'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.\n\n", "solution": "def multifact(n, d)\n n.step(1, -d).inject( :* )\nend\n\n(1..5).each {|d| puts \"Degree #{d}: #{(1..10).map{|n| multifact(n, d)}.join \"\\t\"}\"}"} {"title": "Multiple distinct objects", "language": "Ruby", "task": "Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.\n\nBy ''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.\n\nBy ''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.\n\nThis 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.\n\nThis task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).\n\nSee also: [[Closures/Value capture]]\n\n", "solution": "[Foo.new] * n # here Foo.new can be any expression that returns a new object\nArray.new(n, Foo.new)"} {"title": "Multisplit", "language": "Ruby", "task": "It is often necessary to split a string into pieces \nbased on several different (potentially multi-character) separator strings, \nwhile still retaining the information about which separators were present in the input. \n\nThis is particularly useful when doing small parsing tasks. \nThe task is to write code to demonstrate this.\n\nThe function (or procedure or method, as appropriate) should \ntake an input string and an ordered collection of separators. \n\nThe order of the separators is significant: \nThe delimiter order represents priority in matching, with the first defined delimiter having the highest priority. \nIn cases where there would be an ambiguity as to \nwhich separator to use at a particular point \n(e.g., because one separator is a prefix of another) \nthe separator with the highest priority should be used. \nDelimiters can be reused and the output from the function should be an ordered sequence of substrings.\n\nTest your code using the input string \"a!===b=!=c\" and the separators \"==\", \"!=\" and \"=\".\n\nFor 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\". \nNote that the quotation marks are shown for clarity and do not form part of the output.\n\n'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.\n\n", "solution": "def multisplit(text, separators)\n sep_regex = Regexp.union(separators)\n separator_info = []\n pieces = []\n i = prev = 0\n while i = text.index(sep_regex, i)\n separator = Regexp.last_match(0)\n pieces << text[prev .. i-1]\n separator_info << [separator, i]\n i = i + separator.length\n prev = i\n end\n pieces << text[prev .. -1]\n [pieces, separator_info]\nend\n\np multisplit(text, separators)\n# => [[\"a\", \"\", \"b\", \"\", \"c\"], [[\"!=\", 1], [\"==\", 3], [\"=\", 6], [\"!=\", 7]]]"} {"title": "Mutex", "language": "Ruby", "task": "{{requires|Concurrency}}\n\n\nA '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1. \nA mutex is said to be seized by a [[task]] decreasing ''k''. \nIt is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access. \nA [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.\n\nA 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). \nEntering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down. \n\n=Variants of mutexes=\n\n==Global and local mutexes==\nUsually 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.\n\n==Reentrant mutex==\nA 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.\n\n==Read write mutex==\nA 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.\n\n=Deadlock prevention=\nThere 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.\n\n=Sample implementations / APIs=\n", "solution": "# acquire a lock -- block execution until it becomes free\nan_object.mu_lock\n\n# acquire a lock -- return immediately even if not acquired\ngot_lock = an_object.mu_try_lock\n\n# have a lock?\nif an_object.mu_locked? then ...\n\n# release the lock\nan_object.mu_unlock\n\n# wrap a lock around a block of code -- block execution until it becomes free\nan_object.my_synchronize do\n do critical stuff\nend"} {"title": "N-queens problem", "language": "Ruby", "task": "right\n\nSolve the eight queens puzzle. \n\n\nYou can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.\n \nFor the number of solutions for small values of '''N''', see OEIS: A000170.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[Peaceful chess queen armies]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "# 1. Divide n by 12. Remember the remainder (n is 8 for the eight queens\n# puzzle).\n# 2. Write a list of the even numbers from 2 to n in order.\n# 3. If the remainder is 3 or 9, move 2 to the end of the list.\n# 4. Append the odd numbers from 1 to n in order, but, if the remainder is 8,\n# switch pairs (i.e. 3, 1, 7, 5, 11, 9, \u2026).\n# 5. If the remainder is 2, switch the places of 1 and 3, then move 5 to the\n# end of the list.\n# 6. If the remainder is 3 or 9, move 1 and 3 to the end of the list.\n# 7. Place the first-column queen in the row with the first number in the\n# list, place the second-column queen in the row with the second number in\n# the list, etc.\n\n\ndef n_queens(n)\n if n == 1\n return \"Q\"\n elsif n < 4\n puts \"no solutions for n=#{n}\"\n return \"\"\n end\n \n evens = (2..n).step(2).to_a\n odds = (1..n).step(2).to_a\n \n rem = n % 12 # (1)\n nums = evens # (2)\n \n nums.rotate if rem == 3 or rem == 9 # (3)\n \n # (4)\n if rem == 8\n odds = odds.each_slice(2).flat_map(&:reverse)\n end\n nums.concat(odds)\n \n # (5)\n if rem == 2\n nums[nums.index(1)], nums[nums.index(3)] = nums[nums.index(3)], nums[nums.index(1)]\n nums << nums.delete(5)\n end\n \n # (6)\n if rem == 3 or rem == 9\n nums << nums.delete(1)\n nums << nums.delete(3)\n end\n \n # (7)\n nums.map do |q|\n a = Array.new(n,\".\")\n a[q-1] = \"Q\"\n a*(\" \")\n end\nend\n \n(1 .. 15).each {|n| puts \"n=#{n}\"; puts n_queens(n); puts}"} {"title": "Narcissist", "language": "Ruby", "task": "Quoting from the Esolangs wiki page:\n\n\nA '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].\n\nA 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.\n\n\nFor concreteness, in this task we shall assume that symbol = character. \n\nThe narcissist should be able to cope with any finite input, whatever its length. \n\nAny form of output is allowed, as long as the program always halts, and \"accept\", \"reject\" and \"not yet finished\" are distinguishable.\n\n", "solution": "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')"} {"title": "Narcissistic decimal number", "language": "Ruby", "task": "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.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "class Integer\n def narcissistic?\n return false if negative?\n digs = self.digits \n m = digs.size\n digs.map{|d| d**m}.sum == self\n end\nend\n\nputs 0.step.lazy.select(&:narcissistic?).first(25)"} {"title": "Nautical bell", "language": "Ruby", "task": "Task\n\nWrite a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.\n\nThe bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.\n\nIt 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. \n\n\n;Related task:\n* [[Sleep]]\n\n", "solution": "watches = [ \"First\", \"Middle\", \"Morning\", \"Forenoon\", \"Afternoon\", \"First dog\", \"Last dog\", \"First\" ]\nwatch_ends = [ \"00:00\", \"04:00\", \"08:00\", \"12:00\", \"16:00\", \"18:00\", \"20:00\", \"23:59\" ]\nwords = [\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\"]\nsound = \"ding!\"\n\nloop do\n time = Time.now\n if time.sec == 0 and time.min % 30 == 0\n num = (time.hour * 60 + time.min) / 30 % 8\n num = 8 if num == 0\n hr_min = time.strftime \"%H:%M\"\n idx = watch_ends.find_index {|t| hr_min <= t}\n text = \"%s - %s watch, %s bell%s gone\" % [\n hr_min, \n watches[idx], \n words[num-1], \n num==1 ? \"\" : \"s\"\n ]\n bells = (sound * num).gsub(sound + sound) {|dd| dd + ' '}\n puts \"%-45s %s\" % [text, bells]\n end\n sleep 1\nend"} {"title": "Negative base numbers", "language": "Ruby 2.3", "task": "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\n\n\n;Task:\n\n*Encode the decimal number 10 as negabinary (expect 11110)\n*Encode the decimal number 146 as negaternary (expect 21102)\n*Encode the decimal number 15 as negadecimal (expect 195)\n*In each of the above cases, convert the encoded number back to decimal.\n\n\n;extra credit:\n\n* 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.\n\n", "solution": "DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n\n# convert a base 10 integer into a negative base value (as a string)\n\ndef negative_base_encode(n, b)\n raise 'base out of range' if (b < -62) || (b > -2)\n return '0' if n == 0\n revdigs = []\n while n != 0 do\n n, r = n.divmod(b)\n if r < 0\n n += 1\n r -= b\n end\n revdigs << r\n end\n return revdigs.reduce('') { |digstr, digit| DIGITS[digit] + digstr }\nend\n\n# convert a negative base value (as a string) into a base 10 integer\n\ndef negative_base_decode(n, b)\n raise 'base out of range' if (b < -62) || (b > -2)\n value = 0\n n.reverse.each_char.with_index do |ch, inx|\n value += DIGITS.index(ch) * b**inx\n end\n return value\nend\n\n# do the task\n\n[ [10, -2], [146, -3], [15, -10], [0, -31], [-6221826, -62] ].each do |pair|\n decimal, base = pair\n encoded = negative_base_encode(decimal, base)\n decoded = negative_base_decode(encoded, base)\n puts(\"Enc: %8i base %-3i = %5s base %-3i Dec: %5s base %-3i = %8i base %-3i\" %\n [decimal, 10, encoded, base, encoded, base, decoded, 10])\nend"} {"title": "Nested function", "language": "Ruby", "task": "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.\n\n\n;Task: \nWrite a program consisting of two nested functions that prints the following text.\n\n 1. first\n 2. second\n 3. third\n\nThe 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.\n\nThe 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.\n\n\n;References:\n:* Nested function\n\n", "solution": "def makeList(separator)\n counter = 1\n\n makeItem = lambda {|item|\n result = \"#{counter}#{separator}#{item}\\n\"\n counter += 1\n result\n }\n\n makeItem[\"first\"] + makeItem[\"second\"] + makeItem[\"third\"]\nend\n\nprint makeList(\". \")"} {"title": "Nim game", "language": "Ruby", "task": "Nim is a simple game where the second player-if they know the trick-will always win.\n\n\nThe game has only 3 rules:\n::* start with '''12''' tokens\n::* each player takes '''1, 2, or 3''' tokens in turn\n::* the player who takes the last token wins.\n\n\nTo 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. \n\n;Task:\nDesign a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.\n\n", "solution": "[12, 8, 4].each do |remaining|\n puts \"There are #{remaining} dots.\\nHow many dots would you like to take? \"\n unless (num=gets.to_i).between?(1, 3)\n puts \"Please enter one of 1, 2 or 3\"\n redo\n end\n puts \"You took #{num} dots, leaving #{remaining-num}.\\nComputer takes #{4-num}.\\n\\n\"\nend\n\nputs \"Computer took the last and wins.\"\n"} {"title": "Nonoblock", "language": "Ruby", "task": "Nonogram puzzle.\n\n\n;Given:\n* The number of cells in a row.\n* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.\n\n\n;Task: \n* show all possible positions. \n* show the number of positions of the blocks for the following cases within the row. \n* show all output on this page. \n* use a \"neat\" diagram of the block positions.\n\n\n;Enumerate the following configurations:\n# '''5''' cells and '''[2, 1]''' blocks\n# '''5''' cells and '''[]''' blocks (no blocks)\n# '''10''' cells and '''[8]''' blocks\n# '''15''' cells and '''[2, 3, 2, 3]''' blocks\n# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)\n\n\n;Example:\nGiven 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:\n\n |_|_|_|_|_| # 5 cells and [2, 1] blocks\n\nAnd would expand to the following 3 possible rows of block positions:\n\n |A|A|_|B|_|\n |A|A|_|_|B|\n |_|A|A|_|B|\n\n\nNote how the sets of blocks are always separated by a space.\n\nNote also that it is not necessary for each block to have a separate letter. \nOutput approximating\n\nThis:\n |#|#|_|#|_|\n |#|#|_|_|#|\n |_|#|#|_|#|\n\nThis would also work:\n ##.#.\n ##..#\n .##.#\n\n\n;An algorithm:\n* 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).\n* 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.\n* 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.\n\n(This is the algorithm used in the [[Nonoblock#Python]] solution). \n\n\n;Reference:\n* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "def nonoblocks(cell, blocks)\n raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1\n nblock(cell, blocks, '', [])\nend\n\ndef nblock(cell, blocks, position, result)\n if cell <= 0\n result << position[0..cell-1]\n elsif blocks.empty? or blocks[0].zero?\n result << position + '.' * cell\n else\n rest = cell - blocks.inject(:+) - blocks.size + 2\n bl, *brest = blocks\n rest.times.inject(result) do |res, i|\n nblock(cell-i-bl-1, brest, position + '.'*i + '#'*bl + '.', res)\n end\n end\nend\n\nconf = [[ 5, [2, 1]],\n [ 5, []],\n [10, [8]],\n [15, [2, 3, 2, 3]],\n [ 5, [2, 3]], ]\nconf.each do |cell, blocks|\n begin\n puts \"#{cell} cells and #{blocks} blocks\"\n result = nonoblocks(cell, blocks)\n puts result, result.size, \"\"\n rescue => e\n p e\n end\nend"} {"title": "Numbers which are the cube roots of the product of their proper divisors", "language": "Ruby", "task": "Example\nConsider 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.\n\n;Task\nCompute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.\n\nAlso show the '''500th''' and '''5,000th''' such numbers.\n\n;Stretch\nCompute and show the '''50,000th''' such number.\n\n;Reference\n* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.\n\n;Note\nOEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.\n\n", "solution": "require 'prime'\n\ndef tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp+1}\na111398 = [1].chain (1..).lazy.select{|n| tau(n) == 8}\n\nputs \"The first 50 numbers which are the cube roots of the products of their proper divisors:\"\np a111398.first(50)\n[500, 5000, 50000].each{|n| puts \"#{n}th: #{a111398.drop(n-1).next}\" }\n"} {"title": "Numbers with equal rises and falls", "language": "Ruby", "task": "When a number is written in base 10, adjacent digits may \"rise\" or \"fall\" as the number is read (usually from left to right).\n\n\n;Definition:\nGiven the decimal digits of the number are written as a series d:\n:* A ''rise'' is an index i such that d(i) < d(i+1)\n:* A ''fall'' is an index i such that d(i) > d(i+1)\n\n\n;Examples:\n:* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence.\n:* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence.\n\n\n;Task:\n:* Print the first '''200''' numbers in the sequence \n:* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002'''\n\n\n;See also:\n* OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal \"rises\" and \"falls\".\n\n\n;Related tasks:\n* Esthetic numbers\n\n", "solution": "class Integer\n def eq_rise_fall? = digits.each_cons(2).sum{|a,b| a <=> b} == 0\nend\n\nputs (1..).lazy.select(&:eq_rise_fall?).take(200).force.join(\" \")\n\nn = 10_000_000\nres = (1..).lazy.select(&:eq_rise_fall?).take(n).drop(n-1).first\nputs \"The #{n}th number in the sequence is #{res}.\"\n"} {"title": "Numeric error propagation", "language": "Ruby", "task": "If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; \nthen if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, \nthen sf can be calculated as follows:\n\n:;Addition/Subtraction\n:* If f = a +- c, or f = c +- a then '''sf = sa'''\n:* If f = a +- b then '''sf2 = sa2 + sb2'''\n\n:;Multiplication/Division\n:* If f = ca or f = ac then '''sf = |csa|'''\n:* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)'''\n\n:;Exponentiation\n:* If f = ac then '''sf = |fc(sa / a)|'''\n\n\nCaution:\n::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue.\n\n\n;Task details:\n# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.\n# Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2 \n# Print and display both '''d''' and its error.\n\n \n\n;References:\n* A Guide to Error Propagation B. Keeney, 2005.\n* Propagation of uncertainty Wikipedia.\n\n\n;Related task:\n* [[Quaternion type]]\n\n", "solution": "class NumberWithUncertainty\n def initialize(number, error)\n @num = number\n @err = error.abs\n end\n attr_reader :num, :err\n\n def +(other)\n if other.kind_of?(self.class)\n self.class.new(num + other.num, Math::hypot(err, other.err))\n else\n self.class.new(num + other, err)\n end\n end\n\n def -(other)\n if other.kind_of?(self.class)\n self.class.new(num - other.num, Math::hypot(err, other.err))\n else\n self.class.new(num - other, err)\n end\n end\n\n def *(other)\n if other.kind_of?(self.class)\n prod = num * other.num\n e = Math::hypot((prod * err / num), (prod * other.err / other.num))\n self.class.new(prod, e)\n else\n self.class.new(num * other, (err * other).abs)\n end\n end\n\n def /(other)\n if other.kind_of?(self.class)\n quo = num / other.num\n e = Math::hypot((quo * err / num), (quo * other.err / other.num))\n self.class.new(quo, e)\n else\n self.class.new(num / other, (err * other).abs)\n end\n end\n\n def **(exponent)\n Float(exponent) rescue raise ArgumentError, \"not an number: #{exponent}\"\n prod = num ** exponent\n self.class.new(prod, (prod * exponent * err / num).abs)\n end\n\n def sqrt\n self ** 0.5\n end\n\n def to_s\n \"#{num} \\u00b1 #{err}\"\n end\nend\n\nx1 = NumberWithUncertainty.new(100, 1.1)\ny1 = NumberWithUncertainty.new( 50, 1.2)\nx2 = NumberWithUncertainty.new(200, 2.2)\ny2 = NumberWithUncertainty.new(100, 2.3)\n\nputs ((x1 - x2) ** 2 + (y1 - y2) ** 2).sqrt"} {"title": "Odd word problem", "language": "Ruby", "task": "Write a program that solves the odd word problem with the restrictions given below.\n\n\n;Description:\nYou are promised an input stream consisting of English letters and punctuations. \n\nIt is guaranteed that:\n* the words (sequence of consecutive letters) are delimited by one and only one punctuation,\n* the stream will begin with a word,\n* the words will be at least one letter long, and \n* a full stop (a period, [.]) appears after, and only after, the last word.\n\n\n;Example:\nA stream with six words: \n:: what,is,the;meaning,of:life. \n\n\nThe task is to reverse the letters in every other word while leaving punctuations intact, producing:\n:: what,si,the;gninaem,of:efil. \nwhile observing the following restrictions:\n# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;\n# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;\n# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.\n\n\n;Test cases:\nWork on both the \"life\" example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "These Ruby programs store each character in a single-character string.\n\n===Using fibers and recursion===\n"} {"title": "Odd word problem", "language": "Ruby 1.9", "task": "Write a program that solves the odd word problem with the restrictions given below.\n\n\n;Description:\nYou are promised an input stream consisting of English letters and punctuations. \n\nIt is guaranteed that:\n* the words (sequence of consecutive letters) are delimited by one and only one punctuation,\n* the stream will begin with a word,\n* the words will be at least one letter long, and \n* a full stop (a period, [.]) appears after, and only after, the last word.\n\n\n;Example:\nA stream with six words: \n:: what,is,the;meaning,of:life. \n\n\nThe task is to reverse the letters in every other word while leaving punctuations intact, producing:\n:: what,si,the;gninaem,of:efil. \nwhile observing the following restrictions:\n# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;\n# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;\n# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.\n\n\n;Test cases:\nWork on both the \"life\" example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "f, r = nil\nfwd = proc {|c|\n c =~ /[[:alpha:]]/ ? [(print c), fwd[Fiber.yield f]][1] : c }\nrev = proc {|c|\n c =~ /[[:alpha:]]/ ? [rev[Fiber.yield r], (print c)][0] : c }\n\n(f = Fiber.new { loop { print fwd[Fiber.yield r] }}).resume\n(r = Fiber.new { loop { print rev[Fiber.yield f] }}).resume\n\ncoro = f\nuntil $stdin.eof?\n coro = coro.resume($stdin.getc)\nend"} {"title": "Old Russian measure of length", "language": "Ruby", "task": "Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).\n\n\nIt is an example of a linear transformation of several variables. \n\n\nThe program should accept a single value in a selected unit of measurement, and convert and return it to the other units: \n''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.\n\n\n;Also see:\n:* Old Russian measure of length\n\n", "solution": "module Distances\n\n RATIOS = \n {arshin: 0.7112, centimeter: 0.01, diuym: 0.0254,\n fut: 0.3048, kilometer: 1000.0, liniya: 0.00254,\n meter: 1.0, milia: 7467.6, piad: 0.1778,\n sazhen: 2.1336, tochka: 0.000254, vershok: 0.04445,\n versta: 1066.8}\n\n def self.method_missing(meth, arg)\n from, to = meth.to_s.split(\"2\").map(&:to_sym)\n raise NoMethodError, meth if ([from,to]-RATIOS.keys).size > 0\n RATIOS[from] * arg / RATIOS[to]\n end\n\n def self.print_others(name, num)\n puts \"#{num} #{name} =\"\n RATIOS.except(name.to_sym).each {|k,v| puts \"#{ (1.0 / v*num)} #{k}\" }\n end\nend\n\nDistances.print_others(\"meter\", 2)\nputs\np Distances.meter2centimeter(3)\np Distances.arshin2meter(1)\np Distances.versta2kilometer(20) # en Hoeperdepoep zat op de stoep\n# 13*13 = 169 methods supported, but not:\np Distances.mile2piad(1) \n"} {"title": "Old lady swallowed a fly", "language": "Ruby", "task": "Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. \n\nThis song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.\n\n\n\n", "solution": "descriptions = {\n :fly => \"I don't know why S\",\n :spider => \"That wriggled and jiggled and tickled inside her.\",\n :bird => \"Quite absurd T\",\n :cat => \"Fancy that, S\",\n :dog => \"What a hog, S\",\n :goat => \"She opened her throat T\",\n :cow => \"I don't know how S\",\n :horse => \"She's dead, of course.\",\n}\nanimals = descriptions.keys\n\nanimals.each_with_index do |animal, idx|\n puts \"There was an old lady who swallowed a #{animal}.\"\n\n d = descriptions[animal]\n case d[-1]\n when \"S\" then d[-1] = \"she swallowed a #{animal}.\"\n when \"T\" then d[-1] = \"to swallow a #{animal}.\"\n end\n puts d\n break if animal == :horse\n\n idx.downto(1) do |i|\n puts \"She swallowed the #{animals[i]} to catch the #{animals[i-1]}.\"\n case animals[i-1]\n when :spider, :fly then puts descriptions[animals[i-1]]\n end\n end\n\n print \"Perhaps she'll die.\\n\\n\"\nend"} {"title": "One of n lines in a file", "language": "Ruby", "task": "A method of choosing a line randomly from a file:\n::* Without reading the file more than once\n::* When substantial parts of the file cannot be held in memory\n::* Without knowing how many lines are in the file\nIs to:\n::* keep the first line of the file as a possible choice, then\n::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.\n::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.\n::* ...\n::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N\n\n::* Return the computed possible choice when no further lines exist in the file.\n\n\n;Task:\n# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.\n# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.\n# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.\n\n\nNote: You may choose a smaller number of repetitions if necessary, but mention this up-front.\n\nNote: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling\n\n", "solution": "# Returns a random line from _io_, or nil if _io_ has no lines.\n# # Get a random line from /etc/passwd\n# line = open(\"/etc/passwd\") {|f| random_line(f) }\ndef random_line(io)\n choice = io.gets; count = 1\n while line = io.gets\n rand(count += 1).zero? and choice = line\n end\n choice\nend\n\ndef one_of_n(n)\n # Create a mock IO that provides line numbers instead of lines.\n # Assumes that #random_line calls #gets.\n (mock_io = Object.new).instance_eval do\n @count = 0\n @last = n\n def self.gets\n (@count < @last) ? (@count += 1) : nil\n end\n end\n random_line(mock_io)\nend\n\nchosen = Hash.new(0)\n1_000_000.times { chosen[one_of_n(10)] += 1 }\nchosen.keys.sort.each do |key|\n puts \"#{key} chosen #{chosen[key]} times\"\nend"} {"title": "Operator precedence", "language": "Ruby", "task": "Operators in C and C++}}\n\n\n;Task:\nProvide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. \n\nOperators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. \n\nState whether arguments are passed by value or by reference.\n\n", "solution": "Ruby operators, by precedence (high to low), with arity (N), associativity (A), and definability (D)\n\n{| class=\"wikitable\"\n! Operator(s)\t|| N\t|| A\t|| D\t|| Operation\n|-\n| ! ~ +\t || 1\t|| R\t|| Y\t|| Boolean NOT, bitwise complement, unary plus\n|-\n| **\t || 2\t|| R\t|| Y\t|| Exponentiation\n|-\n| -\t || 1\t|| R\t|| Y\t|| Unary minus (define with -@)\n|-\n| * / %\t || 2\t|| L\t|| Y\t|| Multiplication, division, modulo (remainder)\n|-\n| + -\t || 2\t|| L\t|| Y\t|| Addition (or concatenation), subtraction\n|-\n| << >>\t || 2\t|| L\t|| Y\t|| Bitwise shift-left (or append), bitwise shift-right\n|-\n| &\t || 2\t|| L\t|| Y\t|| Bitwise AND\n|-\n| | ^\t || 2\t|| L\t|| Y\t|| Bitwise OR, bitwise XOR\n|-\n| < <= >= >\t|| 2\t|| L\t|| Y\t|| Ordering\n|-\n| | == === != =~ !~ <=> \t|| 2 || N\t|| Y\t|| Equality, pattern matching, comparison\n|-\n| &&\t || 2\t|| L\t|| N\t|| Boolean AND\n|-\n| || || 2\t|| L\t|| N\t|| Boolean OR\n|-\n| .. ...\t|| 2\t|| N\t|| N\t|| Range creation and Boolean flip-flops\n|-\n| ? :\t || 3 || R\t|| N || Conditional\n|-\n| rescue\t|| 2\t|| L\t|| N\t|| Exception-handling modifier\n|-\n| = **= *= / = %= += -= <<= >>= &&= &= ^= || 2\t|| R\t|| N\t|| Assignment\n|-\n| defined?\t|| 1\t|| N\t|| N\t|| Test variable definition and type\n|-\n| not\t || 1 || R || N\t|| Boolean NOT (low precedence)\n|-\n| and or\t|| 2\t|| L\t|| N\t|| Boolean AND, Boolean OR (low precedence)\n|-\n| if unless while until \t|| 2\t|| N\t|| N\t|| Conditional and loop modifiers\n|}\n\n"} {"title": "Padovan sequence", "language": "Ruby", "task": "The Fibonacci sequence in several ways.\nSome are given in the table below, and the referenced video shows some of the geometric\nsimilarities.\n\n::{| class=\"wikitable\"\n! Comment !! Padovan !! Fibonacci\n|-\n| || || \n|-\n| Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci\n|-\n| || || \n|-\n| Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1\n|-\n| Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2)\n|-\n| || || \n|-\n| First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34\n|-\n| || || \n|-\n| Ratio of successive terms... || Plastic ratio, p || Golden ratio, g\n|-\n| || 1.324717957244746025960908854... || 1.6180339887498948482...\n|-\n| Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2\n|-\n| Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1\n|-\n| || || \n|-\n| Spirally tiling the plane using. || Equilateral triangles || Squares\n|-\n| || || \n|-\n| Constants for ... || s= 1.0453567932525329623 || a=5**0.5\n|-\n| ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5)\n|-\n| || || \n|-\n| L-System Variables. || A,B,C || A,B\n|-\n| L-System Start/Axiom. || A || A\n|-\n| L-System Rules. || A->B,B->C,C->AB || A->B,B->AB\n|}\n\n;Task:\n* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.\n* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.\n* Show the first twenty terms of the sequence.\n* Confirm that the recurrence and floor based functions give the same results for 64 terms,\n* Write a function/method/... using the L-system to generate successive strings.\n* Show the first 10 strings produced from the L-system\n* Confirm that the length of the first 32 strings produced is the Padovan sequence.\n\nShow output here, on this page.\n\n;Ref:\n* The Plastic Ratio - Numberphile video.\n\n\n", "solution": "padovan = Enumerator.new do |y|\n ar = [1, 1, 1]\n loop do\n ar << ar.first(2).sum\n y << ar.shift\n end\nend\n\nP, S = 1.324717957244746025960908854, 1.0453567932525329623\ndef padovan_f(n) = (P**(n-1) / S + 0.5).floor\n \nputs \"Recurrence Padovan: #{padovan.take(20)}\"\nputs \"Floor function: #{(0...20).map{|n| padovan_f(n)}}\"\n\nn = 63\nbool = (0...n).map{|n| padovan_f(n)} == padovan.take(n)\nputs \"Recurrence and floor function are equal upto #{n}: #{bool}.\"\nputs\n \ndef l_system(axiom = \"A\", rules = {\"A\" => \"B\", \"B\" => \"C\", \"C\" => \"AB\"} )\n return enum_for(__method__, axiom, rules) unless block_given? \n loop do\n yield axiom \n axiom = axiom.chars.map{|c| rules[c] }.join\n end\nend\n \nputs \"First 10 elements of L-system: #{l_system.take(10).join(\", \")} \"\nn = 32\nbool = l_system.take(n).map(&:size) == padovan.take(n)\nputs \"Sizes of first #{n} l_system strings equal to recurrence padovan? #{bool}.\"\n"} {"title": "Palindrome dates", "language": "Ruby", "task": "Today ('''2020-02-02''', at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the '''yyyy-mm-dd''' format but, unusually, also for countries which use the '''dd-mm-yyyy''' format.\n\n\n;Task\nWrite a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.\n\n", "solution": "require 'date'\n\npalindate = Enumerator.new do |yielder|\n (\"2020\"..).each do |y|\n m, d = y.reverse.scan(/../) # let the Y10K kids handle 5 digit years\n strings = [y, m, d]\n yielder << strings.join(\"-\") if Date.valid_date?( *strings.map( &:to_i ) )\n end\nend\n\nputs palindate.take(15)"} {"title": "Palindromic gapful numbers", "language": "Ruby from Crystal", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''1037''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''1037'''. \n\n\nA palindromic number is (for this task, a positive integer expressed in base ten), when the number is \nreversed, is the same as the original number.\n\n\n;Task:\n:* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with:\n:::* the digit '''1'''\n:::* the digit '''2'''\n:::* the digit '''3'''\n:::* the digit '''4'''\n:::* the digit '''5'''\n:::* the digit '''6'''\n:::* the digit '''7'''\n:::* the digit '''8'''\n:::* the digit '''9'''\n:* Show (nine sets, like above) of palindromic gapful numbers:\n:::* the last '''15''' palindromic gapful numbers (out of '''100''')\n:::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional}\n\n\nFor other ways of expressing the (above) requirements, see the ''discussion'' page.\n\n\n;Note:\nAll palindromic gapful numbers are divisible by eleven. \n\n\n;Related tasks:\n:* palindrome detection.\n:* gapful numbers.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n\n", "solution": "class PalindromicGapfuls\n include Enumerable\n\n def initialize(digit)\n @digit = digit\n @nn = @digit * 11 # digit gapful divisor: 11, 22,...88, 99\n end\n\n def each\n power = 1 # these two lines will work\n while power += 1 # for all Ruby VMs|versions\n #(2..).each do |power| # Ruby => 2.6; can replace above 2 lines\n base = 10**(power >> 1) # value of middle digit position: 10..\n base11 = base * 11 # value of middle two digits positions: 110..\n this_lo = base * @digit # starting half for this digit: 10.. to 90..\n next_lo = base * (@digit + 1) # starting half for next digit: 20.. to 100..\n this_lo.step(to: next_lo - 1, by: 10) do |front_half| # d_00; d_10; d_20; ...\n left_half = front_half.to_s; right_half = left_half.reverse\n if power.odd?\n palindrome = (left_half + right_half).to_i\n 10.times do\n yield palindrome if palindrome % @nn == 0\n palindrome += base11\n end\n else\n palindrome = (left_half.chop + right_half).to_i\n 10.times do\n yield palindrome if palindrome % @nn == 0\n palindrome += base\n end \n end\n end\n end\n end\n\n # Optimized output method: only keep desired values.\n def keep_from(count, keep)\n to_skip = (count - keep)\n kept = []\n each_with_index do |value, i|\n i < to_skip ? next : kept << value\n return kept if kept.size == keep\n end\n end\nend\n\nstart = Time.now\n\ncount, keep = 20, 20\nputs \"First 20 palindromic gapful numbers ending with:\"\n1.upto(9) { |digit| puts \"#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}\" }\n\ncount, keep = 100, 15\nputs \"\\nLast 15 of first 100 palindromic gapful numbers ending in:\"\n1.upto(9) { |digit| puts \"#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}\" }\n\ncount, keep = 1_000, 10\nputs \"\\nLast 10 of first 1000 palindromic gapful numbers ending in:\"\n1.upto(9) { |digit| puts \"#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}\" }\n\ncount, keep = 100_000, 1\nputs \"\\n100,000th palindromic gapful number ending with:\"\n1.upto(9) { |digit| puts \"#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}\" }\n\ncount, keep = 1_000_000, 1\nputs \"\\n1,000,000th palindromic gapful number ending with:\"\n1.upto(9) { |digit| puts \"#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}\" }\n\ncount, keep = 10_000_000, 1\nputs \"\\n10,000,000th palindromic gapful number ending with:\"\n1.upto(9) { |digit| puts \"#{digit} : #{PalindromicGapfuls.new(digit).keep_from(count, keep)}\" }\n\nputs (Time.now - start)"} {"title": "Palindromic gapful numbers", "language": "Ruby from F#", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''1037''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''1037'''. \n\n\nA palindromic number is (for this task, a positive integer expressed in base ten), when the number is \nreversed, is the same as the original number.\n\n\n;Task:\n:* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with:\n:::* the digit '''1'''\n:::* the digit '''2'''\n:::* the digit '''3'''\n:::* the digit '''4'''\n:::* the digit '''5'''\n:::* the digit '''6'''\n:::* the digit '''7'''\n:::* the digit '''8'''\n:::* the digit '''9'''\n:* Show (nine sets, like above) of palindromic gapful numbers:\n:::* the last '''15''' palindromic gapful numbers (out of '''100''')\n:::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional}\n\n\nFor other ways of expressing the (above) requirements, see the ''discussion'' page.\n\n\n;Note:\nAll palindromic gapful numbers are divisible by eleven. \n\n\n;Related tasks:\n:* palindrome detection.\n:* gapful numbers.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n\n", "solution": "class PalNo\n def initialize(set)\n @set, @l=set, 3\n end\n def fN(n)\n return [0,1,2,3,4,5,6,7,8,9] if n==1\n return [0,11,22,33,44,55,66,77,88,99] if n==2\n a=[]; [0,1,2,3,4,5,6,7,8,9].product(fN(n-2)).each{|g| a.push(g[0]*10**(n-1)+g[0]+10*g[1])}; return a\n end\n def each\n while true do fN(@l-2).each{|g| a=@set*10**(@l-1)+@set+10*g; yield a if a%(11*@set)==0}; @l+=1 end\n end\nend\n\nfor n in 1..9 do palNo=PalNo.new(n); g=1; palNo.each{|n| print \"#{n} \"; g+=1; break unless g<21}; puts \"\" end; puts \"####\"\nfor n in 1..9 do palNo=PalNo.new(n); g=1; palNo.each{|n| print \"#{n} \" if g>85; g+=1; break unless g<101}; puts \"\" end; puts \"####\"\nfor n in 1..9 do palNo=PalNo.new(n); g=1; palNo.each{|n| print \"#{n} \" if g>990; g+=1; break unless g<1001}; puts \"\" end; puts \"####\"\n"} {"title": "Palindromic gapful numbers", "language": "Ruby from Ruby of F#", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''1037''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''1037'''. \n\n\nA palindromic number is (for this task, a positive integer expressed in base ten), when the number is \nreversed, is the same as the original number.\n\n\n;Task:\n:* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with:\n:::* the digit '''1'''\n:::* the digit '''2'''\n:::* the digit '''3'''\n:::* the digit '''4'''\n:::* the digit '''5'''\n:::* the digit '''6'''\n:::* the digit '''7'''\n:::* the digit '''8'''\n:::* the digit '''9'''\n:* Show (nine sets, like above) of palindromic gapful numbers:\n:::* the last '''15''' palindromic gapful numbers (out of '''100''')\n:::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional}\n\n\nFor other ways of expressing the (above) requirements, see the ''discussion'' page.\n\n\n;Note:\nAll palindromic gapful numbers are divisible by eleven. \n\n\n;Related tasks:\n:* palindrome detection.\n:* gapful numbers.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n\n", "solution": "class PalNo\n def initialize(digit)\n @digit, @l, @dd = digit, 3, 11*digit\n end\n def fN(n)\n return [0,1,2,3,4,5,6,7,8,9] if n==1\n return [0,11,22,33,44,55,66,77,88,99] if n==2\n a=[]; [0,1,2,3,4,5,6,7,8,9].product(fN(n-2)).each{ |g0,g1| a << g0*10**(n-1)+g0+10*g1 }; return a\n end\n def show(count, keep)\n to_skip, palcnt, pals = count - keep, 0, []\n while palcnt < count\n fN(@l-2).each{ |g| pal=@digit*10**(@l-1)+@digit+10*g;\n pals << pal if pal%(@dd)==0 && (palcnt += 1) > to_skip; break if palcnt - to_skip == keep }; @l+=1\n end\n print pals; puts\n end\nend\n\nstart = Time.now\n\n(1..9).each { |digit| PalNo.new(digit).show(20, 20) }; puts \"####\"\n(1..9).each { |digit| PalNo.new(digit).show(100, 15) }; puts \"####\"\n(1..9).each { |digit| PalNo.new(digit).show(1000, 10) }; puts \"####\"\n(1..9).each { |digit| PalNo.new(digit).show(100_000, 1) }; puts \"####\"\n(1..9).each { |digit| PalNo.new(digit).show(1_000_000, 1) }; puts \"####\"\n(1..9).each { |digit| PalNo.new(digit).show(10_000_000, 1) }; puts \"####\"\n\nputs (Time.now - start)"} {"title": "Pancake numbers", "language": "Ruby from C", "task": "Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.\n\nThe task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.\n\n[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?\n\nFew people know p(20), generously I shall award an extra credit for anyone doing more than p(16).\n\n\n;References\n# Bill Gates and the pancake problem\n# A058986\n\n", "solution": "def pancake(n)\n gap = 2\n sum = 2\n adj = -1\n while sum < n\n adj = adj + 1\n gap = gap * 2 - 1\n sum = sum + gap\n end\n return n + adj\nend\n\nfor i in 0 .. 3\n for j in 1 .. 5\n n = i * 5 + j\n print \"p(%2d) = %2d \" % [n, pancake(n)]\n end\n print \"\\n\"\nend"} {"title": "Pangram checker", "language": "Ruby", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: ''The quick brown fox jumps over the lazy dog''.\n\n\n;Task:\nWrite a function or method to check a sentence to see if it is a pangram (or not) and show its use.\n\n\n;Related tasks:\n:* determine if a string has all the same characters\n:* determine if a string has all unique characters\n\n", "solution": "def pangram?(sentence)\n s = sentence.downcase\n ('a'..'z').all? {|char| s.include? (char) }\nend\n\np pangram?('this is a sentence') # ==> false\np pangram?('The quick brown fox jumps over the lazy dog.') # ==> true"} {"title": "Paraffins", "language": "Ruby from Python", "task": "This organic chemistry task is essentially to implement a tree enumeration algorithm.\n\n\n;Task:\nEnumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). \n\n\nParaffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the \"backbone\" structure, with adding hydrogen atoms linking the remaining unused bonds.\n\nIn a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with '''n''' carbon atoms share the empirical formula CnH2n+2\n\nBut for all '''n''' >= 4 there are several distinct molecules (\"isomers\") with the same formula but different structures. \n\nThe number of isomers rises rather rapidly when '''n''' increases. \n\nIn counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D \"out of the paper\" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.\n\n\n;Example:\nWith '''n''' = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with '''n''' = 4 there are two configurations: \n:::* a straight chain: (CH3)(CH2)(CH2)(CH3) \n:::* a branched chain: (CH3)(CH(CH3))(CH3)\n\nDue to bond rotations, it doesn't matter which direction the branch points in. \n\nThe phenomenon of \"stereo-isomerism\" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.\n\nThe input is the number '''n''' of carbon atoms of a molecule (for instance '''17'''). \n\nThe output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17).\n\nThe sequence of those results is visible in the OEIS entry: \n::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. \n\nThe sequence is (the index starts from zero, and represents the number of carbon atoms):\n\n 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,\n 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,\n 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,\n 10660307791, 27711253769, ...\n\n\n;Extra credit:\nShow the paraffins in some way. \n\nA flat 1D representation, with arrays or lists is enough, for instance:\n\n*Main> all_paraffins 1\n [CCP H H H H]\n*Main> all_paraffins 2\n [BCP (C H H H) (C H H H)]\n*Main> all_paraffins 3\n [CCP H H (C H H H) (C H H H)]\n*Main> all_paraffins 4\n [BCP (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 5\n [CCP H H (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 6\n [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),\n BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),\n BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),\n CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]\nShowing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):\n methane ethane propane isobutane\n \n H H H H H H H H H\n | | | | | | | | |\n H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H\n | | | | | | | | |\n H H H H H H H | H\n |\n H - C - H\n |\n H \n\n;Links:\n* A paper that explains the problem and its solution in a functional language:\nhttp://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf\n\n* A Haskell implementation:\nhttps://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs\n\n* A Scheme implementation:\nhttp://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm\n\n* A Fortress implementation: (this site has been closed)\nhttp://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005\n\n", "solution": "MAX_N = 500\nBRANCH = 4\n\ndef tree(br, n, l=n, sum=1, cnt=1)\n for b in br+1 .. BRANCH\n sum += n\n return if sum >= MAX_N\n # prevent unneeded long math\n return if l * 2 >= sum and b >= BRANCH\n if b == br + 1\n c = $ra[n] * cnt\n else\n c = c * ($ra[n] + (b - br - 1)) / (b - br)\n end\n $unrooted[sum] += c if l * 2 < sum\n next if b >= BRANCH\n $ra[sum] += c\n (1...n).each {|m| tree(b, m, l, sum, c)}\n end\nend\n\ndef bicenter(s)\n return if s.odd?\n aux = $ra[s / 2]\n $unrooted[s] += aux * (aux + 1) / 2\nend\n\n$ra = [0] * MAX_N\n$unrooted = [0] * MAX_N\n\n$ra[0] = $ra[1] = $unrooted[0] = $unrooted[1] = 1\nfor n in 1...MAX_N\n tree(0, n)\n bicenter(n)\n puts \"%d: %d\" % [n, $unrooted[n]]\nend"} {"title": "Parse an IP Address", "language": "Ruby", "task": "The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.\n \n\nTaking the following as inputs:\n::: {| border=\"5\" cellspacing=\"0\" cellpadding=2\n|-\n|127.0.0.1\n|The \"localhost\" IPv4 address\n|-\n|127.0.0.1:80\n|The \"localhost\" IPv4 address, with a specified port (80)\n|-\n|::1\n|The \"localhost\" IPv6 address\n|-\n|[::1]:80\n|The \"localhost\" IPv6 address, with a specified port (80)\n|-\n|2605:2700:0:3::4713:93e3\n|Rosetta Code's primary server's public IPv6 address\n|-\n|[2605:2700:0:3::4713:93e3]:80\n|Rosetta Code's primary server's public IPv6 address, with a specified port (80)\n|}\n\n\n;Task:\nEmit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. \n\nIn languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.\n\n\n;Example:\n'''127.0.0.1''' has the address number '''7F000001''' (2130706433 decimal) \nin the ipv4 address space. \n\n'''::ffff:127.0.0.1''' represents the same address in the ipv6 address space where it has the \naddress number '''FFFF7F000001''' (281472812449793 decimal). \n\n'''::1''' has address number '''1''' and serves the same purpose in the ipv6 address \nspace that '''127.0.0.1''' serves in the ipv4 address space.\n\n", "solution": "require 'ipaddr'\n\n \nTESTCASES = [\"127.0.0.1\", \"127.0.0.1:80\",\n \"::1\", \"[::1]:80\",\n \"2605:2700:0:3::4713:93e3\", \"[2605:2700:0:3::4713:93e3]:80\"] \n\noutput = [%w(String Address Port Family Hex),\n %w(------ ------- ---- ------ ---)]\n\ndef output_table(rows)\n widths = []\n rows.each {|row| row.each_with_index {|col, i| widths[i] = [widths[i].to_i, col.to_s.length].max }}\n format = widths.map {|size| \"%#{size}s\"}.join(\"\\t\")\n rows.each {|row| puts format % row}\nend\n\nTESTCASES.each do |str|\n case str # handle port; IPAddr does not.\n when /\\A\\[(?
.* )\\]:(? \\d+ )\\z/x # string like \"[::1]:80\"\n address, port = $~[:address], $~[:port]\n when /\\A(?
[^:]+ ):(? \\d+ )\\z/x # string like \"127.0.0.1:80\"\n address, port = $~[:address], $~[:port]\n else # string with no port number\n address, port = str, nil\n end\n \n ip_addr = IPAddr.new(address) \n family = \"IPv4\" if ip_addr.ipv4?\n family = \"IPv6\" if ip_addr.ipv6?\n\n output << [str, ip_addr.to_s, port.to_s, family, ip_addr.to_i.to_s(16)]\nend\n\noutput_table(output)"} {"title": "Parsing/RPN calculator algorithm", "language": "Ruby", "task": "Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.\n\n\n* Assume an input of a correct, space separated, string of tokens of an RPN expression\n* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: \n 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* '''^''' means exponentiation in the expression above.\n* '''/''' means division.\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* [[Parsing/RPN to infix conversion]].\n* [[Arithmetic evaluation]].\n\n", "solution": "rpn = RPNExpression(\"3 4 2 * 1 5 - 2 3 ^ ^ / +\")\nvalue = rpn.eval"} {"title": "Parsing/Shunting-yard algorithm", "language": "Ruby", "task": "Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "rpn = RPNExpression.from_infix(\"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\")"} {"title": "Pascal's triangle/Puzzle", "language": "Ruby", "task": "This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.\n\n [ 151]\n [ ][ ]\n [40][ ][ ]\n [ ][ ][ ][ ]\n [ X][11][ Y][ 4][ Z]\n\nEach brick of the pyramid is the sum of the two bricks situated below it.\nOf the three missing numbers at the base of the pyramid, \nthe middle one is the sum of the other two (that is, Y = X + Z).\n\n\n;Task:\nWrite a program to find a solution to this puzzle.\n\n", "solution": "require 'rref'\n\npyramid = [\n [ 151],\n [nil,nil],\n [40,nil,nil],\n [nil,nil,nil,nil],\n [\"x\", 11,\"y\", 4,\"z\"]\n]\npyramid.each{|row| p row}\n\nequations = [[1,-1,1,0]] # y = x + z\n\ndef parse_equation(str)\n eqn = [0] * 4\n lhs, rhs = str.split(\"=\")\n eqn[3] = rhs.to_i\n for term in lhs.split(\"+\")\n case term\n when \"x\" then eqn[0] += 1\n when \"y\" then eqn[1] += 1\n when \"z\" then eqn[2] += 1\n else eqn[3] -= term.to_i\n end\n end\n eqn \nend\n\n-2.downto(-5) do |row|\n pyramid[row].each_index do |col|\n val = pyramid[row][col]\n sum = \"%s+%s\" % [pyramid[row+1][col], pyramid[row+1][col+1]]\n if val.nil?\n pyramid[row][col] = sum\n else\n equations << parse_equation(sum + \"=#{val}\")\n end\n end\nend\n\nreduced = convert_to(reduced_row_echelon_form(equations), :to_i)\n\nfor eqn in reduced\n if eqn[0] + eqn[1] + eqn[2] != 1\n fail \"no unique solution! #{equations.inspect} ==> #{reduced.inspect}\"\n elsif eqn[0] == 1 then x = eqn[3]\n elsif eqn[1] == 1 then y = eqn[3]\n elsif eqn[2] == 1 then z = eqn[3]\n end\nend\n\nputs\nputs \"x == #{x}\"\nputs \"y == #{y}\"\nputs \"z == #{z}\"\n\nanswer = []\nfor row in pyramid\n answer << row.collect {|cell| eval cell.to_s}\nend\nputs\nanswer.each{|row| p row}"} {"title": "Pascal matrix generation", "language": "Ruby", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.\n\nShown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. \n\nA Pascal upper-triangular matrix that is populated with jCi:\n\n[[1, 1, 1, 1, 1],\n [0, 1, 2, 3, 4],\n [0, 0, 1, 3, 6],\n [0, 0, 0, 1, 4],\n [0, 0, 0, 0, 1]]\n\n\nA Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):\n\n[[1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0],\n [1, 2, 1, 0, 0],\n [1, 3, 3, 1, 0],\n [1, 4, 6, 4, 1]]\n\n\nA Pascal symmetric matrix that is populated with i+jCi:\n\n[[1, 1, 1, 1, 1],\n [1, 2, 3, 4, 5],\n [1, 3, 6, 10, 15],\n [1, 4, 10, 20, 35],\n [1, 5, 15, 35, 70]]\n\n\n\n;Task:\nWrite functions capable of generating each of the three forms of n-by-n matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "#Upper, lower, and symetric Pascal Matrix - Nigel Galloway: May 3rd., 21015\nrequire 'pp'\n\nng = (g = 0..4).collect{[]}\ng.each{|i| g.each{|j| ng[i][j] = i==0 ? 1 : j z\n upper-case letters: A --> Z\n digits: 0 --> 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include ''at least one'' (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), and \n one \"other\" character. \n\n\nThe user must be able to specify the password length and the number of passwords to generate. \n\nThe passwords should be displayed or written to a file, one per line.\n\nThe randomness should be from a system source or library. \n\nThe program should implement a help option or button which should describe the program and options when invoked. \n\nYou may also allow the user to specify a seed value, and give the option of excluding visually similar characters.\n\nFor example: Il1 O0 5S 2Z where the characters are: \n::::* capital eye, lowercase ell, the digit one\n::::* capital oh, the digit zero \n::::* the digit five, capital ess\n::::* the digit two, capital zee\n\n\n", "solution": "ARRS = [(\"a\"..\"z\").to_a,\n (\"A\"..\"Z\").to_a, \n (\"0\"..\"9\").to_a,\n %q(!\"#$%&'()*+,-./:;<=>?@[]^_{|}~).chars] # \" quote to reset clumsy code colorizer\nALL = ARRS.flatten\n\ndef generate_pwd(size, num)\n raise ArgumentError, \"Desired size too small\" unless size >= ARRS.size\n num.times.map do\n arr = ARRS.map(&:sample)\n (size - ARRS.size).times{ arr << ALL.sample}\n arr.shuffle.join\n end\nend\n\nputs generate_pwd(8,3)\n"} {"title": "Pathological floating point problems", "language": "Ruby", "task": "Most programmers are familiar with the inexactness of floating point calculations in a binary processor. \n\nThe classic example being:\n\n0.1 + 0.2 = 0.30000000000000004\n\n\nIn many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.\n\nThere are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.\n\nThis task's purpose is to show how your language deals with such classes of problems.\n\n\n'''A sequence that seems to converge to a wrong limit.''' \n\nConsider the sequence:\n:::::: v1 = 2 \n:::::: v2 = -4 \n:::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2) \n\n\nAs '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''.\n\n\n;Task 1:\nDisplay the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places.\n\n n = 3 18.5\n n = 4 9.378378\n n = 5 7.801153\n n = 6 7.154414\n n = 7 6.806785\n n = 8 6.5926328\n n = 20 6.0435521101892689\n n = 30 6.006786093031205758530554\n n = 50 6.0001758466271871889456140207471954695237\n n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266\n\n\n\n;Task 2:\n'''The Chaotic Bank Society''' is offering a new investment account to their customers. \n\nYou first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.\n\nAfter each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. \n\nSo ...\n::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.\n::* after 2 years your balance will be doubled and $1 removed.\n::* after 3 years your balance will be tripled and $1 removed.\n::* ... \n::* after 10 years, multiplied by 10 and $1 removed, and so on. \n\n\nWhat will your balance be after 25 years?\n Starting balance: $e-1\n Balance = (Balance * year) - 1 for 25 years\n Balance after 25 years: $0.0399387296732302\n\n\n;Task 3, extra credit:\n'''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988.\n:::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) \n:::::: compute f(a,b) where a=77617.0 and b=33096.0 \n:::::: f(77617.0, 33096.0) = -0.827396059946821 \n\n\nDemonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.\n\n\n;See also;\n* Floating-Point Arithmetic Section 1.3.2 Difficult problems.\n\n", "solution": "ar = [0, 2, -4]\n100.times{ar << (111 - 1130.quo(ar[-1])+ 3000.quo(ar[-1]*ar[-2])) }\n \n[3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n|\n puts \"%3d -> %0.16f\" % [n, ar[n]]\nend\n"} {"title": "Peaceful chess queen armies", "language": "Ruby from Java", "task": "In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.\n\n\n\n\n\\\n|\n/\n\n\n\n=\n=\n\n=\n=\n\n\n\n/\n|\n\\\n\n\n\n/\n\n|\n\n\\\n\n\n\n\n|\n\n\n\n\n\n\nThe goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.\n\n\n;Task:\n# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).\n# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.\n# Display here results for the m=4, n=5 case.\n\n\n;References:\n* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.\n* A250000 OEIS\n\n", "solution": "class Position\n attr_reader :x, :y\n\n def initialize(x, y)\n @x = x\n @y = y\n end\n\n def ==(other)\n self.x == other.x &&\n self.y == other.y\n end\n\n def to_s\n '(%d, %d)' % [@x, @y]\n end\n\n def to_str\n to_s\n end\nend\n\ndef isAttacking(queen, pos)\n return queen.x == pos.x ||\n queen.y == pos.y ||\n (queen.x - pos.x).abs() == (queen.y - pos.y).abs()\nend\n\ndef place(m, n, blackQueens, whiteQueens)\n if m == 0 then\n return true\n end\n placingBlack = true\n for i in 0 .. n-1\n for j in 0 .. n-1\n catch :inner do\n pos = Position.new(i, j)\n for queen in blackQueens\n if pos == queen || !placingBlack && isAttacking(queen, pos) then\n throw :inner\n end\n end\n for queen in whiteQueens\n if pos == queen || placingBlack && isAttacking(queen, pos) then\n throw :inner\n end\n end\n if placingBlack then\n blackQueens << pos\n placingBlack = false\n else\n whiteQueens << pos\n if place(m - 1, n, blackQueens, whiteQueens) then\n return true\n end\n blackQueens.pop\n whiteQueens.pop\n placingBlack = true\n end\n end\n end\n end\n if !placingBlack then\n blackQueens.pop\n end\n return false\nend\n\ndef printBoard(n, blackQueens, whiteQueens)\n # initialize the board\n board = Array.new(n) { Array.new(n) { ' ' } }\n for i in 0 .. n-1\n for j in 0 .. n-1\n if i % 2 == j % 2 then\n board[i][j] = '\u2022'\n else\n board[i][j] = '\u25e6'\n end\n end\n end\n\n # insert the queens\n for queen in blackQueens\n board[queen.y][queen.x] = 'B'\n end\n for queen in whiteQueens\n board[queen.y][queen.x] = 'W'\n end\n\n # print the board\n for row in board\n for cell in row\n print cell, ' '\n end\n print \"\\n\"\n end\n print \"\\n\"\nend\n\nnms = [\n [2, 1],\n [3, 1], [3, 2],\n [4, 1], [4, 2], [4, 3],\n [5, 1], [5, 2], [5, 3], [5, 4], [5, 5],\n [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6],\n [7, 1], [7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [7, 7]\n]\nfor nm in nms\n m = nm[1]\n n = nm[0]\n print \"%d black and %d white queens on a %d x %d board:\\n\" % [m, m, n, n]\n\n blackQueens = []\n whiteQueens = []\n if place(m, n, blackQueens, whiteQueens) then\n printBoard(n, blackQueens, whiteQueens)\n else\n print \"No solution exists.\\n\\n\"\n end\nend"} {"title": "Perfect shuffle", "language": "Ruby", "task": "A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:\n\n\n\n::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K\n\n\n\nWhen you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:\n\n\n\n::::: {| style=\"border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right\"\n|-\n| ''original:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|-\n| ''after 1st shuffle:'' ||\n1\n5\n2\n6\n3\n7\n4\n8\n|-\n| ''after 2nd shuffle:'' ||\n1\n3\n5\n7\n2\n4\n6\n8\n|-\n| ''after 3rd shuffle:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|}\n\n\n'''''The Task'''''\n\n# Write a function that can perform a perfect shuffle on an even-sized list of values.\n# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under \"Test Cases\" below.\n#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all \"cards\" are unique within each deck.\n#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.\n'''''Test Cases'''''\n\n::::: {| class=\"wikitable\"\n|-\n! input ''(deck size)'' !! output ''(number of shuffles required)''\n|-\n| 8 || 3\n|-\n| 24 || 11\n|-\n| 52 || 8\n|-\n| 100 || 30\n|-\n| 1020 || 1018\n|-\n| 1024 || 10\n|-\n| 10000 || 300\n|}\n\n", "solution": "def perfect_shuffle(deck_size = 52)\n deck = (1..deck_size).to_a\n original = deck.dup\n half = deck_size / 2\n 1.step do |i|\n deck = deck.first(half).zip(deck.last(half)).flatten\n return i if deck == original \n end\nend\n\n[8, 24, 52, 100, 1020, 1024, 10000].each {|i| puts \"Perfect shuffles required for deck size #{i}: #{perfect_shuffle(i)}\"}\n"} {"title": "Perfect totient numbers", "language": "Ruby", "task": "Generate and show here, the first twenty Perfect totient numbers.\n\n\n;Related task:\n::* [[Totient function]]\n\n\n;Also see:\n::* the OEIS entry for perfect totient numbers.\n::* mrob list of the first 54\n\n", "solution": "require \"prime\"\n\nclass Integer \n\n def \u03c6\n prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) } \n end\n\n def perfect_totient?\n f, sum = self, 0\n until f == 1 do\n f = f.\u03c6\n sum += f\n end\n self == sum\n end\n\nend\n\nputs (1..).lazy.select(&:perfect_totient?).first(20).join(\", \")\n"} {"title": "Permutations/Derangements", "language": "Ruby", "task": "A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.\n\nFor example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).\n\nThe number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. \nThere are various ways to calculate !''n''.\n\n\n;Task:\n# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer). \n# Generate ''and show'' all the derangements of 4 integers using the above routine.\n# Create a function that calculates the subfactorial of ''n'', !''n''.\n# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.\n\n\n;Optional stretch goal:\n* Calculate !''20'' \n\n\n;Related tasks:\n* [[Anagrams/Deranged anagrams]]\n* [[Best shuffle]]\n* [[Left_factorials]]\n\n\n\n", "solution": "def derangements(n)\n ary = (1 .. n).to_a\n ary.permutation.select do |perm|\n ary.zip(perm).all? {|a,b| a != b}\n end\nend\n\ndef subfact(n)\n case n\n when 0 then 1\n when 1 then 0\n else (n-1)*(subfact(n-1) + subfact(n-2))\n end\nend\n\nputs \"derangements for n = 4\"\nderangements(4).each{|d|p d}\n\nputs \"\\n n derange subfact\"\n(0..9).each do |n|\n puts \"%2d :%8d,%8d\" % [n, derangements(n).size, subfact(n)]\nend\n\nputs \"\\nNumber of derangements\"\n(10..20).each do |n|\n puts \"#{n} : #{subfact(n)}\"\nend"} {"title": "Permutations/Rank of a permutation", "language": "Ruby", "task": "A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. \nFor our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1).\n\nFor example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:\n\n PERMUTATION RANK\n (0, 1, 2, 3) -> 0\n (0, 1, 3, 2) -> 1\n (0, 2, 1, 3) -> 2\n (0, 2, 3, 1) -> 3\n (0, 3, 1, 2) -> 4\n (0, 3, 2, 1) -> 5\n (1, 0, 2, 3) -> 6\n (1, 0, 3, 2) -> 7\n (1, 2, 0, 3) -> 8\n (1, 2, 3, 0) -> 9\n (1, 3, 0, 2) -> 10\n (1, 3, 2, 0) -> 11\n (2, 0, 1, 3) -> 12\n (2, 0, 3, 1) -> 13\n (2, 1, 0, 3) -> 14\n (2, 1, 3, 0) -> 15\n (2, 3, 0, 1) -> 16\n (2, 3, 1, 0) -> 17\n (3, 0, 1, 2) -> 18\n (3, 0, 2, 1) -> 19\n (3, 1, 0, 2) -> 20\n (3, 1, 2, 0) -> 21\n (3, 2, 0, 1) -> 22\n (3, 2, 1, 0) -> 23\n\nAlgorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).\n\nOne use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.\n\nA question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.\n\n\n;Task:\n# Create a function to generate a permutation from a rank.\n# Create the inverse function that given the permutation generates its rank.\n# Show that for n=3 the two functions are indeed inverses of each other.\n# Compute and show here 4 random, individual, samples of permutations of 12 objects.\n\n\n;Stretch goal:\n* State how reasonable it would be to use your program to address the limits of the Stack Overflow question.\n\n\n;References:\n# Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).\n# Ranks on the DevData site.\n# Another answer on Stack Overflow to a different question that explains its algorithm in detail.\n\n;Related tasks:\n#[[Factorial_base_numbers_indexing_permutations_of_a_collection]]\n\n", "solution": "class Permutation\n include Enumerable\n attr_reader :num_elements, :size\n \n def initialize(num_elements)\n @num_elements = num_elements\n @size = fact(num_elements)\n end\n \n def each\n return self.to_enum unless block_given?\n (0...@size).each{|i| yield unrank(i)}\n end\n \n def unrank(r) # nonrecursive version of Myrvold Ruskey unrank2 algorithm.\n pi = (0...num_elements).to_a\n (@num_elements-1).downto(1) do |n|\n s, r = r.divmod(fact(n))\n pi[n], pi[s] = pi[s], pi[n]\n end\n pi\n end\n \n def rank(pi) # nonrecursive version of Myrvold Ruskey rank2 algorithm.\n pi = pi.dup\n pi1 = pi.zip(0...pi.size).sort.map(&:last)\n (pi.size-1).downto(0).inject(0) do |memo,i|\n pi[i], pi[pi1[i]] = pi[pi1[i]], (s = pi[i])\n pi1[s], pi1[i] = pi1[i], pi1[s]\n memo += s * fact(i)\n end\n end\n \n private\n def fact(n)\n n.zero? ? 1 : n.downto(1).inject(:*)\n end\nend"} {"title": "Permutations by swapping", "language": "Ruby from BBC BASIC", "task": "Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. \n\nAlso generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. \n\nShow the permutations and signs of three items, in order of generation ''here''.\n\nSuch data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.\n\nNote: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus-Johnson-Trotter algorithm\n* Johnson-Trotter Algorithm Listing All Permutations\n* Heap's algorithm\n* Tintinnalogia\n\n\n;Related tasks:\n* [[Matrix arithmetic]\n* [[Gray code]]\n\n", "solution": "def perms(n)\n p = Array.new(n+1){|i| -i}\n s = 1\n loop do\n yield p[1..-1].map(&:abs), s\n k = 0\n for i in 2..n\n k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs\n end\n for i in 1...n\n k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs\n end\n break if k.zero?\n for i in 1..n\n p[i] *= -1 if p[i].abs > p[k].abs\n end\n i = k + (p[k] <=> 0)\n p[k], p[i] = p[i], p[k]\n s = -s\n end\nend\n\nfor i in 3..4\n perms(i){|perm, sign| puts \"Perm: #{perm} Sign: #{sign}\"}\n puts\nend"} {"title": "Phrase reversals", "language": "Ruby", "task": "Given a string of space separated words containing the following phrase:\n rosetta code phrase reversal\n\n:# Reverse the characters of the string.\n:# Reverse the characters of each individual word in the string, maintaining original word order within the string.\n:# Reverse the order of each word of the string, maintaining the order of characters in each word.\n\nShow your output here.\n \n\n\n", "solution": "str = \"rosetta code phrase reversal\"\n\nputs str.reverse # Reversed string.\nputs str.split.map(&:reverse).join(\" \") # Words reversed.\nputs str.split.reverse.join(\" \") # Word order reversed."} {"title": "Pig the dice game", "language": "Ruby", "task": "The game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach '''100''' points or more. \nPlay is taken in turns. On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.\n\n\n;Task:\nCreate a program to score for, and simulate dice throws for, a two-person game. \n\n\n;Related task:\n* [[Pig the dice game/Player]]\n\n", "solution": "class PigGame\n Player = Struct.new(:name, :safescore, :score) do\n def bust!() self.score = safescore end\n def stay!() self.safescore = score end\n def to_s() \"#{name} (#{safescore}, #{score})\" end\n end\n \n def initialize(names, maxscore=100, die_sides=6)\n rotation = names.map {|name| Player.new(name,0,0) }\n \n rotation.cycle do |player|\n loop do\n if wants_to_roll?(player)\n puts \"Rolled: #{roll=roll_dice(die_sides)}\"\n if bust?(roll)\n puts \"Busted!\",''\n player.bust!\n break\n else\n player.score += roll\n if player.score >= maxscore\n puts player.name + \" wins!\"\n return\n end\n end\n else\n player.stay!\n puts \"Staying with #{player.safescore}!\", ''\n break\n end\n end\n end\n end\n \n def roll_dice(die_sides) rand(1..die_sides) end\n def bust?(roll) roll==1 end\n def wants_to_roll?(player)\n print \"#{player}: Roll? (Y) \"\n ['Y','y',''].include?(gets.chomp)\n end\nend\n\nPigGame.new( %w|Samuel Elizabeth| )"} {"title": "Pig the dice game/Player", "language": "Ruby", "task": "Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy.\n* State here the play strategies involved.\n* Show play during a game here.\n\n\nAs a stretch goal:\n* Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.\n\n\n;Game Rules:\nThe game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach 100 points or more.\nPlay is taken in turns. On each person's turn that person has the option of either\n\n# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n# '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.\n\n\n;References\n* Pig (dice)\n* The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.\n\n", "solution": "def player1(sum,sm)\nfor i in 1..100\nputs \"player1 rolled\"\na=gets.chomp().to_i\nif (a>1 && a<7)\n\tsum+=a\n\tif sum>=100\n\tputs \"player1 wins\"\n\tbreak\n\tend\nelse\n\ngoto player2(sum,sm)\nend\ni+=1\nend\nend\n\ndef player2(sum,sm)\nfor j in 1..100\nputs \"player2 rolled\"\nb=gets.chomp().to_i\nif(b>1 && b<7)\n sm+=b\n\tif sm>=100\n\t puts \"player2 wins\"\n\tbreak\n\tend\nelse\n\nplayer1(sum,sm)\nend\nj+=1\nend\nend\ni=0\nj=0\nsum=0\nsm=0\nplayer1(sum,sm)\nreturn"} {"title": "Playfair cipher", "language": "Ruby", "task": "Implement a Playfair cipher for encryption and decryption.\n\n\nThe user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet.\n\nThe output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.\n\n\n;Output example:\n HI DE TH EG OL DI NT HE TR EX ES TU MP\n\n", "solution": "class Playfair\n Size = 5\n def initialize(key, missing)\n @missing = missing.upcase\n alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''\n extended = key.upcase.gsub(/[^A-Z]/,'').split('') + alphabet\n grid = extended.uniq[0...Size*Size].each_slice(Size).to_a\n coords = {}\n grid.each_with_index do |row, i|\n row.each_with_index do |letter, j|\n coords[letter] = [i,j]\n end\n end\n @encode = {}\n alphabet.product(alphabet).reject { |a,b| a==b }.each do |a, b|\n i1, j1 = coords[a]\n i2, j2 = coords[b]\n if i1 == i2 then\n j1 = (j1 + 1) % Size\n j2 = (j2 + 1) % Size\n elsif j1 == j2 then\n i1 = (i1 + 1) % Size\n i2 = (i2 + 1) % Size\n else\n j1, j2 = j2, j1\n end\n @encode[\"#{a}#{b}\"] = \"#{grid[i1][j1]}#{grid[i2][j2]}\"\n @decode = @encode.invert\n end\n end\n\n def encode(plaintext) \n plain = plaintext.upcase.gsub(/[^A-Z]/,'')\n if @missing == 'J' then\n plain = plain.gsub(/J/, 'I')\n else\n plain = plain.gsub(@missing, 'X')\n end\n plain = plain.gsub(/(.)\\1/, '\\1X\\1')\n if plain.length % 2 == 1 then\n plain += 'X'\n end\n return plain.upcase.split('').each_slice(2).map do |pair|\n @encode[pair.join]\n end.join.split('').each_slice(5).map{|s|s.join}.join(' ')\n end\n\n def decode(ciphertext) \n cipher = ciphertext.upcase.gsub(/[^A-Z]/,'')\n return cipher.upcase.split('').each_slice(2).map do |pair|\n @decode[pair.join]\n end.join.split('').each_slice(5).map{|s|s.join}.join(' ')\n end\nend"} {"title": "Poker hand analyser", "language": "Ruby", "task": "Create a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' (two of diamonds).\n\n\n\nFaces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or \nalternatively, the unicode card-suit characters: \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2 2 2 k q: three-of-a-kind\n 2 5 7 8 9: high-card\n a 2 3 4 5: straight\n 2 3 2 3 3: full-house\n 2 7 2 3 3: two-pair\n 2 7 7 7 7: four-of-a-kind \n 10 j q k a: straight-flush\n 4 4 k 5 10: one-pair\n q 10 7 6 q: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2 2 k q: three-of-a-kind\n joker 5 7 8 9: straight\n joker 2 3 4 5: straight\n joker 3 2 3 3: four-of-a-kind\n joker 7 2 3 3: three-of-a-kind\n joker 7 7 7 7: five-of-a-kind\n joker j q k A: straight-flush\n joker 4 k 5 10: one-pair\n joker k 7 6 4: flush\n joker 2 joker 4 5: straight\n joker Q joker A 10: straight\n joker Q joker A 10: straight-flush\n joker 2 2 joker q: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "class Card\n include Comparable\n attr_accessor :ordinal\n attr_reader :suit, :face \n \n SUITS = %i(\u2665 \u2666 \u2663 \u2660)\n FACES = %i(2 3 4 5 6 7 8 9 10 j q k a)\n \n def initialize(str)\n @face, @suit = parse(str)\n @ordinal = FACES.index(@face)\n end\n \n def <=> (other) #used for sorting\n self.ordinal <=> other.ordinal\n end\n \n def to_s\n \"#@face#@suit\"\n end\n \n private\n def parse(str)\n face, suit = str.chop.to_sym, str[-1].to_sym\n raise ArgumentError, \"invalid card: #{str}\" unless FACES.include?(face) && SUITS.include?(suit)\n [face, suit]\n end\nend\n\nclass Hand\n include Comparable\n attr_reader :cards, :rank\n \n RANKS = %i(high-card one-pair two-pair three-of-a-kind straight flush\n full-house four-of-a-kind straight-flush five-of-a-kind)\n WHEEL_FACES = %i(2 3 4 5 a)\n \n def initialize(str_of_cards)\n @cards = str_of_cards.downcase.tr(',',' ').split.map{|str| Card.new(str)}\n grouped = @cards.group_by(&:face).values\n @face_pattern = grouped.map(&:size).sort\n @rank = categorize\n @rank_num = RANKS.index(@rank)\n @tiebreaker = grouped.map{|ar| [ar.size, ar.first.ordinal]}.sort.reverse\n end\n \n def <=> (other) # used for sorting and comparing\n self.compare_value <=> other.compare_value\n end\n \n def to_s\n @cards.map(&:to_s).join(\" \")\n end\n \n protected # accessible for Hands\n def compare_value\n [@rank_num, @tiebreaker]\n end\n \n private\n def one_suit?\n @cards.map(&:suit).uniq.size == 1\n end\n \n def consecutive?\n sort.each_cons(2).all? {|c1,c2| c2.ordinal - c1.ordinal == 1 }\n end\n \n def sort\n if @cards.sort.map(&:face) == WHEEL_FACES\n @cards.detect {|c| c.face == :a}.ordinal = -1\n end \n @cards.sort\n end\n \n def categorize\n if consecutive?\n one_suit? ? :'straight-flush' : :straight\n elsif one_suit?\n :flush\n else\n case @face_pattern\n when [1,1,1,1,1] then :'high-card'\n when [1,1,1,2] then :'one-pair'\n when [1,2,2] then :'two-pair'\n when [1,1,3] then :'three-of-a-kind'\n when [2,3] then :'full-house'\n when [1,4] then :'four-of-a-kind'\n when [5] then :'five-of-a-kind'\n end\n end\n end\nend\n\n# Demo\ntest_hands = <= 0 && popcount.even?\n end\n\nend\n \nputs \"Powers of 3:\", (0...30).map{|n| (3**n).popcount}.join(' ')\nputs \"Evil:\" , 0.step.lazy.select(&:evil?).first(30).join(' ')\nputs \"Odious:\", 0.step.lazy.reject(&:evil?).first(30).join(' ')"} {"title": "Priority queue", "language": "Ruby", "task": "A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.\n\n\n;Task:\nCreate a priority queue. The queue must support at least two operations:\n:# Insertion. An element is added to the queue with a priority (a numeric value).\n:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.\n\n\nOptionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.\n\n\nTo test your implementation, insert a number of elements into the queue, each with some random priority. \n\nThen dequeue them sequentially; now the elements should be sorted by priority. \n\nYou can use the following task/priority items as input data:\n '''Priority''' '''Task'''\n ---------- ----------------\n 3 Clear drains\n 4 Feed cat\n 5 Make tea\n 1 Solve RC tasks\n 2 Tax return\n\n\nThe implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. \n\nYou may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.\n\n", "solution": "class PriorityQueueNaive\n def initialize(data=nil)\n @q = Hash.new {|h, k| h[k] = []}\n data.each {|priority, item| @q[priority] << item} if data\n @priorities = @q.keys.sort\n end\n \n def push(priority, item)\n @q[priority] << item\n @priorities = @q.keys.sort\n end\n \n def pop\n p = @priorities[0]\n item = @q[p].shift\n if @q[p].empty?\n @q.delete(p)\n @priorities.shift\n end\n item\n end\n \n def peek\n unless empty?\n @q[@priorities[0]][0]\n end\n end\n \n def empty?\n @priorities.empty?\n end\n \n def each\n @q.each do |priority, items|\n items.each {|item| yield priority, item}\n end\n end\n \n def dup\n @q.each_with_object(self.class.new) do |(priority, items), obj|\n items.each {|item| obj.push(priority, item)}\n end\n end\n \n def merge(other)\n raise TypeError unless self.class == other.class\n pq = dup\n other.each {|priority, item| pq.push(priority, item)}\n pq # return a new object\n end\n \n def inspect\n @q.inspect\n end\nend\n\ntest = [\n [6, \"drink tea\"],\n [3, \"Clear drains\"],\n [4, \"Feed cat\"],\n [5, \"Make tea\"],\n [6, \"eat biscuit\"],\n [1, \"Solve RC tasks\"],\n [2, \"Tax return\"],\n]\n\npq = PriorityQueueNaive.new\ntest.each {|pr, str| pq.push(pr, str) }\nuntil pq.empty? \n puts pq.pop\nend\n\nputs\ntest2 = test.shift(3)\np pq1 = PriorityQueueNaive.new(test)\np pq2 = PriorityQueueNaive.new(test2)\np pq3 = pq1.merge(pq2)\nputs \"peek : #{pq3.peek}\"\nuntil pq3.empty?\n puts pq3.pop\nend\nputs \"peek : #{pq3.peek}\""} {"title": "Pseudo-random numbers/Combined recursive generator MRG32k3a", "language": "Ruby from C", "task": "MRG32k3a Combined recursive generator (pseudo-code):\n\n /* Constants */\n /* First generator */\n a1 = [0, 1403580, -810728]\n m1 = 2**32 - 209\n /* Second Generator */\n a2 = [527612, 0, -1370589]\n m2 = 2**32 - 22853\n \n d = m1 + 1\n \n class MRG32k3a\n x1 = [0, 0, 0] /* list of three last values of gen #1 */\n x2 = [0, 0, 0] /* list of three last values of gen #2 */\n \n method seed(u64 seed_state)\n assert seed_state in range >0 and < d \n x1 = [seed_state, 0, 0]\n x2 = [seed_state, 0, 0]\n end method\n \n method next_int()\n x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1\n x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2\n x1 = [x1i, x1[0], x1[1]] /* Keep last three */\n x2 = [x2i, x2[0], x2[1]] /* Keep last three */\n z = (x1i - x2i) % m1\n answer = (z + 1)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / d\n end method\n \n end class\n \n:MRG32k3a Use:\n random_gen = instance MRG32k3a\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 1459213977 */\n print(random_gen.next_int()) /* 2827710106 */\n print(random_gen.next_int()) /* 4245671317 */\n print(random_gen.next_int()) /* 3877608661 */\n print(random_gen.next_int()) /* 2595287583 */\n \n \n;Task\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers generated with the seed `1234567`\nare as shown above \n\n* Show that for an initial seed of '987654321' the counts of 100_000\nrepetitions of\n\n floor(random_gen.next_float() * 5)\n\nIs as follows:\n \n 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931\n\n* Show your output here, on this page.\n\n\n", "solution": "def mod(x, y)\n m = x % y\n if m < 0 then\n if y < 0 then\n return m - y\n else\n return m + y\n end\n end\n return m\nend\n\n# Constants\n# First generator\nA1 = [0, 1403580, -810728]\nA1.freeze\nM1 = (1 << 32) - 209\n# Second generator\nA2 = [527612, 0, -1370589]\nA2.freeze\nM2 = (1 << 32) - 22853\n\nD = M1 + 1\n\n# the last three values of the first generator\n$x1 = [0, 0, 0]\n# the last three values of the second generator\n$x2 = [0, 0, 0]\n\ndef seed(seed_state)\n $x1 = [seed_state, 0, 0]\n $x2 = [seed_state, 0, 0]\nend\n\ndef next_int()\n x1i = mod((A1[0] * $x1[0] + A1[1] * $x1[1] + A1[2] * $x1[2]), M1)\n x2i = mod((A2[0] * $x2[0] + A2[1] * $x2[1] + A2[2] * $x2[2]), M2)\n z = mod(x1i - x2i, M1)\n\n $x1 = [x1i, $x1[0], $x1[1]]\n $x2 = [x2i, $x2[0], $x2[1]]\n\n return z + 1\nend\n\ndef next_float()\n return 1.0 * next_int() / D\nend\n\n########################################\n\nseed(1234567)\nprint next_int(), \"\\n\"\nprint next_int(), \"\\n\"\nprint next_int(), \"\\n\"\nprint next_int(), \"\\n\"\nprint next_int(), \"\\n\"\nprint \"\\n\"\n\ncounts = [0, 0, 0, 0, 0]\nseed(987654321)\nfor i in 1 .. 100000\n value = (next_float() * 5.0).floor\n counts[value] = counts[value] + 1\nend\ncounts.each_with_index { |v,i|\n print i, \": \", v, \"\\n\"\n}"} {"title": "Pseudo-random numbers/Middle-square method", "language": "Ruby", "task": "{{Wikipedia|Middle-square method|en}}\n; The Method:\nTo generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. \n; Pseudo code:\n\nvar seed = 675248\nfunction random()\n var s = str(seed * seed) 'str: turn a number into string\n do while not len(s) = 12\n s = \"0\" + s 'add zeroes before the string\n end do\n seed = val(mid(s, 4, 6)) 'mid: string variable, start, length\n 'val: turn a string into number\n return seed\nend function\n\n; Middle-square method use:\n\nfor i = 1 to 5\n print random()\nend for\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers (6 digits) as shown above.\n\n* Show the first five integers generated with the seed 675248 as shown above.\n\n* Show your output here, on this page.\n\n", "solution": "def middle_square (seed)\n return to_enum(__method__, seed) unless block_given?\n s = seed.digits.size\n loop { yield seed = (seed*seed).to_s.rjust(s*2, \"0\")[s/2, s].to_i }\nend\n\nputs middle_square(675248).take(5)"} {"title": "Pseudo-random numbers/PCG32", "language": "Ruby from Python", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n:'''|''' Bitwise or operator\n::https://en.wikipedia.org/wiki/Bitwise_operation#OR\n::Bitwise comparison gives 1 if any of corresponding bits are 1\n:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111\n\n\n;PCG32 Generator (pseudo-code):\n\nPCG32 has two unsigned 64-bit integers of internal state:\n# '''state''': All 2**64 values may be attained.\n# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).\n\nValues of sequence allow 2**63 ''different'' sequences of random numbers from the same state.\n\nThe algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-\n\nconst N<-U64 6364136223846793005\nconst inc<-U64 (seed_sequence << 1) | 1\nstate<-U64 ((inc+seed_state)*N+inc\ndo forever\n xs<-U32 (((state>>18)^state)>>27)\n rot<-INT (state>>59)\n OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))\n state<-state*N+inc\nend do\n\nNote that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers using the above.\n\n* Show that the first five integers generated with the seed 42, 54\nare: 2707161783 2068313097 3122475824 2211639955 3215226955\n\n \n\n* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005\n\n* Show your output here, on this page.\n\n\n", "solution": "class PCG32\n MASK64 = (1 << 64) - 1\n MASK32 = (1 << 32) - 1\n CONST = 6364136223846793005\n\n def seed(seed_state, seed_sequence)\n @state = 0\n @inc = ((seed_sequence << 1) | 1) & MASK64\n next_int\n @state = @state + seed_state\n next_int\n end\n \n def next_int\n old = @state\n @state = ((old * CONST) + @inc) & MASK64\n xorshifted = (((old >> 18) ^ old) >> 27) & MASK32\n rot = (old >> 59) & MASK32\n answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))\n answer & MASK32\n end\n \n def next_float\n next_int.fdiv(1 << 32)\n end\n \nend\n\nrandom_gen = PCG32.new\nrandom_gen.seed(42, 54)\n5.times{puts random_gen.next_int}\n\nrandom_gen.seed(987654321, 1)\np 100_000.times.each{(random_gen.next_float * 5).floor}.tally.sort.to_h\n"} {"title": "Pseudo-random numbers/Xorshift star", "language": "Ruby", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n;Xorshift_star Generator (pseudo-code):\n\n /* Let u64 denote an unsigned 64 bit integer type. */\n /* Let u32 denote an unsigned 32 bit integer type. */\n \n class Xorshift_star\n u64 state /* Must be seeded to non-zero initial value */\n u64 const = HEX '2545F4914F6CDD1D'\n \n method seed(u64 num):\n state = num\n end method\n \n method next_int():\n u64 x = state\n x = x ^ (x >> 12)\n x = x ^ (x << 25)\n x = x ^ (x >> 27)\n state = x\n u32 answer = ((x * const) >> 32)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / (1 << 32)\n end method\n \n end class\n \n:;Xorshift use:\n\n random_gen = instance Xorshift_star\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 3540625527 */\n print(random_gen.next_int()) /* 2750739987 */\n print(random_gen.next_int()) /* 4037983143 */\n print(random_gen.next_int()) /* 1993361440 */\n print(random_gen.next_int()) /* 3809424708 */\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers genrated with the seed 1234567\nare as shown above \n\n* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007\n\n* Show your output here, on this page.\n\n\n\n", "solution": "class Xorshift_star\n MASK64 = (1 << 64) - 1\n MASK32 = (1 << 32) - 1\n\n def initialize(seed = 0) = @state = seed & MASK64\n\n def next_int\n x = @state\n x = x ^ (x >> 12) \n x = (x ^ (x << 25)) & MASK64\n x = x ^ (x >> 27) \n @state = x\n (((x * 0x2545F4914F6CDD1D) & MASK64) >> 32) & MASK32\n end\n \n def next_float = next_int.fdiv((1 << 32))\n\nend\n\nrandom_gen = Xorshift_star.new(1234567)\n5.times{ puts random_gen.next_int}\n\nrandom_gen = Xorshift_star.new(987654321)\ntally = Hash.new(0)\n100_000.times{ tally[(random_gen.next_float*5).floor] += 1 }\nputs tally.sort.map{|ar| ar.join(\": \") }"} {"title": "Pythagorean quadruples", "language": "Ruby from VBA", "task": "One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): \n\n\n:::::::: a2 + b2 + c2 = d2 \n\n\nAn example:\n\n:::::::: 22 + 32 + 62 = 72 \n\n::::: which is:\n\n:::::::: 4 + 9 + 36 = 49 \n\n\n;Task:\n\nFor positive integers up '''2,200''' (inclusive), for all values of '''a''', \n'''b''', '''c''', and '''d''', \nfind (and show here) those values of '''d''' that ''can't'' be represented.\n\nShow the values of '''d''' on one line of output (optionally with a title).\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]]. \n* [[Pythagorean triples]].\n\n\n;Reference:\n:* the Wikipedia article: Pythagorean quadruple.\n\n", "solution": "n = 2200\nl_add, l = {}, {}\n1.step(n) do |x|\n x2 = x*x \n x.step(n) {|y| l_add[x2 + y*y] = true} \nend\n\ns = 3\n1.step(n) do |x|\n s1 = s\n s += 2\n s2 = s\n (x+1).step(n) do |y|\n l[y] = true if l_add[s1]\n s1 += s2\n s2 += 2\n end\nend\n\nputs (1..n).reject{|x| l[x]}.join(\" \")\n"} {"title": "Pythagorean triples", "language": "Ruby from Java", "task": "A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.\n\nThey are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\\rm gcd}(a, b) = {\\rm gcd}(a, c) = {\\rm gcd}(b, c) = 1. \n\nBecause of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\\rm gcd}(a, b) = 1). \n\nEach triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.\n\n\n;Task:\nThe task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.\n\n\n;Extra credit: \nDeal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]] \n* [[List comprehensions]]\n* [[Pythagorean quadruples]] \n\n", "solution": "class PythagoranTriplesCounter\n def initialize(limit)\n @limit = limit\n @total = 0\n @primitives = 0\n generate_triples(3, 4, 5)\n end\n attr_reader :total, :primitives\n \n private\n def generate_triples(a, b, c)\n perim = a + b + c\n return if perim > @limit\n\n @primitives += 1\n @total += @limit / perim\n\n generate_triples( a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c)\n generate_triples( a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c)\n generate_triples(-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c)\n end\nend\n\nperim = 10\nwhile perim <= 100_000_000 \n c = PythagoranTriplesCounter.new perim\n p [perim, c.total, c.primitives]\n perim *= 10\nend"} {"title": "Quaternion type", "language": "Ruby 1.9", "task": "complex numbers.\n\nA complex number has a real and complex part, sometimes written as a + bi, \nwhere a and b stand for real numbers, and i stands for the square root of minus 1.\n\nAn example of a complex number might be -3 + 2i, \nwhere the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, i, j, and k. \n\nA quaternion might be written as a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* ii = jj = kk = ijk = -1, or more simply,\n:::* ii = jj = kk = ijk = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: q1 and q2: q1q2 q2q1. \n\nAn example of a quaternion might be 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. \n\nSo the example above would be written as (1, 2, 3, 4) \n\n\n;Task:\nGiven the three quaternions and their components: \n q = (1, 2, 3, 4) = (a, b, c, d)\n q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)\n q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) \nAnd a wholly real number r = 7. \n\n\nCreate functions (or classes) to perform simple maths with quaternions including computing:\n# The norm of a quaternion: = \\sqrt{a^2 + b^2 + c^2 + d^2} \n# The negative of a quaternion: = (-a, -b, -c, -d) \n# The conjugate of a quaternion: = ( a, -b, -c, -d) \n# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) \n# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) \n# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) \n# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) \n# Show that, for the two quaternions q1 and q2: q1q2 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* [[Vector products]]\n* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.\n\n", "solution": "class Quaternion\n def initialize(*parts)\n raise ArgumentError, \"wrong number of arguments (#{parts.size} for 4)\" unless parts.size == 4\n raise ArgumentError, \"invalid value of quaternion parts #{parts}\" unless parts.all? {|x| x.is_a?(Numeric)}\n @parts = parts\n end\n \n def to_a; @parts; end\n def to_s; \"Quaternion#{@parts.to_s}\" end\n alias inspect to_s\n def complex_parts; [Complex(*to_a[0..1]), Complex(*to_a[2..3])]; end\n \n def real; @parts.first; end\n def imag; @parts[1..3]; end\n def conj; Quaternion.new(real, *imag.map(&:-@)); end\n def norm; Math.sqrt(to_a.reduce(0){|sum,e| sum + e**2}) end # In Rails: Math.sqrt(to_a.sum { e**2 })\n \n def ==(other)\n case other\n when Quaternion; to_a == other.to_a\n when Numeric; to_a == [other, 0, 0, 0]\n else false\n end\n end\n def -@; Quaternion.new(*to_a.map(&:-@)); end\n def -(other); self + -other; end\n \n def +(other)\n case other\n when Numeric\n Quaternion.new(real + other, *imag)\n when Quaternion\n Quaternion.new(*to_a.zip(other.to_a).map { |x,y| x + y }) # In Rails: zip(other).map(&:sum)\n end\n end\n \n def *(other)\n case other\n when Numeric\n Quaternion.new(*to_a.map { |x| x * other })\n when Quaternion\n # Multiplication of quaternions in C x C space. See \"Cayley-Dickson construction\".\n a, b, c, d = *complex_parts, *other.complex_parts\n x, y = a*c - d.conj*b, a*d + b*c.conj\n Quaternion.new(x.real, x.imag, y.real, y.imag)\n end\n end\n \n # Coerce is called by Ruby to return a compatible type/receiver when the called method/operation does not accept a Quaternion\n def coerce(other)\n case other\n when Numeric then [Scalar.new(other), self]\n else raise TypeError, \"#{other.class} can't be coerced into #{self.class}\"\n end\n end\n \n class Scalar\n def initialize(val); @val = val; end\n def +(other); other + @val; end\n def *(other); other * @val; end\n def -(other); Quaternion.new(@val, 0, 0, 0) - other; end\n end\nend\n\nif __FILE__ == $0\n q = Quaternion.new(1,2,3,4)\n q1 = Quaternion.new(2,3,4,5)\n q2 = Quaternion.new(3,4,5,6)\n r = 7\n expressions = [\"q\", \"q1\", \"q2\",\n \"q.norm\", \"-q\", \"q.conj\", \"q + r\", \"r + q\",\"q1 + q2\", \"q2 + q1\",\n \"q * r\", \"r * q\", \"q1 * q2\", \"q2 * q1\", \"(q1 * q2 != q2 * q1)\",\n \"q - r\", \"r - q\"]\n expressions.each do |exp|\n puts \"%20s = %s\" % [exp, eval(exp)]\n end\nend"} {"title": "RIPEMD-160", "language": "Ruby", "task": "'''RIPEMD-160''' is another hash function; it computes a 160-bit message digest.\n\nThere is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. \nFor padding the message, RIPEMD-160 acts like [[MD4]] (RFC 1320).\n\nFind the RIPEMD-160 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \"Rosetta Code\". \nYou may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.\n\n", "solution": "require 'stringio'\n\nmodule RMD160\n # functions and constants\n MASK = (1 << 32) - 1\n F = [\n proc {|x, y, z| x ^ y ^ z},\n proc {|x, y, z| (x & y) | (x.^(MASK) & z)},\n proc {|x, y, z| (x | y.^(MASK)) ^ z},\n proc {|x, y, z| (x & z) | (y & z.^(MASK))},\n proc {|x, y, z| x ^ (y | z.^(MASK))},\n ].freeze\n K = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]\n KK = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]\n R = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]\n RR = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]\n S = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]\n SS = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]\n\n module_function\n\n def rol(value, shift)\n (value << shift).&(MASK) | (value.&(MASK) >> (32 - shift))\n end\n\n # Calculates RIPEMD-160 message digest of _string_. Returns binary\n # digest. For hexadecimal digest, use\n # +*RMD160.rmd160(string).unpack('H*')+.\n def rmd160(string)\n # initial hash\n h0 = 0x67452301\n h1 = 0xefcdab89\n h2 = 0x98badcfe\n h3 = 0x10325476\n h4 = 0xc3d2e1f0\n\n io = StringIO.new(string)\n block = \"\"\n term = false # appended \"\\x80\" in second-last block?\n last = false # last block?\n until last\n # Read next block of 16 words (64 bytes, 512 bits).\n io.read(64, block) or (\n # Work around a bug in Rubinius 1.2.4. At eof,\n # MRI and JRuby already replace block with \"\".\n block.replace(\"\")\n )\n\n # Unpack block into 32-bit words \"V\".\n case len = block.length\n when 64\n # Unpack 16 words.\n x = block.unpack(\"V16\")\n when 56..63\n # Second-last block: append padding, unpack 16 words.\n block.concat(\"\\x80\"); term = true\n block.concat(\"\\0\" * (63 - len))\n x = block.unpack(\"V16\")\n when 0..55\n # Last block: append padding, unpack 14 words.\n block.concat(term ? \"\\0\" : \"\\x80\")\n block.concat(\"\\0\" * (55 - len))\n x = block.unpack(\"V14\")\n\n # Append bit length, 2 words.\n bit_len = string.length << 3\n x.push(bit_len & MASK, bit_len >> 32)\n last = true\n else\n fail \"impossible\"\n end\n\n # Process this block.\n a, b, c, d, e = h0, h1, h2, h3, h4\n aa, bb, cc, dd, ee = h0, h1, h2, h3, h4\n j = 0\n 5.times {|ro|\n f, ff = F[ro], F[4 - ro]\n k, kk = K[ro], KK[ro]\n 16.times {\n a, e, d, c, b = e, d, rol(c, 10), b,\n rol(a + f[b, c, d] + x[R[j]] + k, S[j]) + e\n aa, ee, dd, cc, bb = ee, dd, rol(cc, 10), bb,\n rol(aa + ff[bb, cc, dd] + x[RR[j]] + kk, SS[j]) + ee\n j += 1\n }\n }\n h0, h1, h2, h3, h4 =\n (h1 + c + dd) & MASK, (h2 + d + ee) & MASK,\n (h3 + e + aa) & MASK, (h4 + a + bb) & MASK,\n (h0 + b + cc) & MASK\n end # until last\n\n [h0, h1, h2, h3, h4].pack(\"V5\")\n end\nend\n\nif __FILE__ == $0\n # Print an example RIPEMD-160 digest.\n str = 'Rosetta Code'\n printf \"%s:\\n %s\\n\", str, *RMD160.rmd160(str).unpack('H*')\nend"} {"title": "RPG attributes generator", "language": "Ruby", "task": "'''RPG''' = Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "res = []\nuntil res.sum >= 75 && res.count{|n| n >= 15} >= 2 do\n res = Array.new(6) do\n a = Array.new(4){rand(1..6)}\n a.sum - a.min\n end\nend\n\np res\nputs \"sum: #{res.sum}\"\n"} {"title": "Ramanujan's constant", "language": "Ruby", "task": "Calculate Ramanujan's constant (as described on the OEIS site) with at least\n32 digits of precision, by the method of your choice. Optionally, if using the e**(p*''x'') approach,\nshow that when evaluated with the last four Heegner numbers\nthe result is ''almost'' an integer.\n\n", "solution": "require \"bigdecimal/math\"\ninclude BigMath\n\ne, pi = E(200), PI(200)\n[19, 43, 67, 163].each do |x|\n puts \"#{x}: #{(e ** (pi * BigMath.sqrt(BigDecimal(x), 200))).round(100).to_s(\"F\")}\"\nend\n"} {"title": "Random Latin squares", "language": "Ruby", "task": "A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.\nFor the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.\n\n;Example n=4 randomised Latin square:\n0 2 3 1\n2 1 0 3\n3 0 1 2\n1 3 2 0\n\n;Task:\n# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.\n# Use the function to generate ''and show here'', two randomly generated squares of size 5.\n\n;Note: \nStrict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.\n\n;Related tasks:\n* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]\n* [[Latin Squares in reduced form]]\n\n;Reference:\n* Wikipedia: Latin square\n* OEIS: A002860\n\n", "solution": "N = 5\n\ndef generate_square\n perms = (1..N).to_a.permutation(N).to_a.shuffle\n square = []\n N.times do\n square << perms.pop\n perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} }\n end\n square\nend\n\ndef print_square(square)\n cell_size = N.digits.size + 1\n strings = square.map!{|row| row.map!{|el| el.to_s.rjust(cell_size)}.join }\n puts strings, \"\\n\"\nend\n\n2.times{print_square( generate_square)}\n"} {"title": "Random number generator (device)", "language": "Ruby", "task": "If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:\n\nshow how to obtain a random 32-bit number from that mechanism.\n\n;Related task\n* [[Random_number_generator_(included)]]\n\n", "solution": "require 'securerandom'\nSecureRandom.random_number(1 << 32)\n\n#or specifying SecureRandom as the desired RNG:\np (1..10).to_a.sample(3, random: SecureRandom) # =>[1, 4, 5]\n"} {"title": "Random number generator (included)", "language": "Ruby", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "Ruby's rand function currently uses the [[wp:Mersenne twister|Mersenne twister]] algorithm, as described in [http://www.ruby-doc.org/core/classes/Kernel.html#M005974 its documentation].\n\n"} {"title": "Range expansion", "language": "Ruby", "task": "{{:Range extraction/Format}}\n\n\n;Task:\nExpand the range description: \n -6,-3--1,3-5,7-11,14,15,17-20 \nNote that the second element above, \nis the '''range from minus 3 to ''minus'' 1'''. \n\n\n;Related task:\n* [[Range extraction]]\n\n", "solution": "def range_expand(rng)\n rng.split(',').flat_map do |part|\n if part =~ /^(-?\\d+)-(-?\\d+)$/\n ($1.to_i .. $2.to_i).to_a\n else\n Integer(part)\n end\n end\nend\n\np range_expand('-6,-3--1,3-5,7-11,14,15,17-20')"} {"title": "Range extraction", "language": "Ruby", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "def range_extract(l)\n # pad the list with a big value, so that the last loop iteration will\n # append something to the range\n sorted, range = l.sort.concat([Float::MAX]), []\n canidate_number = sorted.first\n\n # enumerate over the sorted list in pairs of current number and next by index\n sorted.each_cons(2) do |current_number, next_number|\n # if there is a gap between the current element and its next by index\n if current_number.succ < next_number\n # if current element is our first or our next by index\n if canidate_number == current_number\n # put the first element or next by index into our range as a string\n range << canidate_number.to_s\n else\n # if current element is not the same as the first or next\n # add [first or next, first or next equals current add , else -, current]\n seperator = canidate_number.succ == current_number ? \",\" : \"-\"\n range << \"%d%s%d\" % [canidate_number, seperator, current_number]\n end\n # make the first element the next element\n canidate_number = next_number\n end\n end\n range.join(',')\nend\n\nlst = [\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n]\n\np rng = range_extract(lst)"} {"title": "Range extraction", "language": "Ruby 2.2", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "ary = [0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39]\nputs ary.sort.slice_when{|i,j| i+1 != j}.map{|a| a.size<3 ? a : \"#{a[0]}-#{a[-1]}\"}.join(\",\")"} {"title": "Rate counter", "language": "Ruby", "task": "Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.\nOf interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.\n\nMultiple approaches are allowed (even preferable), so long as they can accomplish these goals:\n\n* Run N seconds worth of jobs and/or Y jobs.\n* Report at least three distinct times.\n\nBe aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.\n\n'''See also:''' [[System time]], [[Time a function]]\n\n", "solution": "require 'benchmark'\nDocument = Struct.new(:id,:a,:b,:c)\ndocuments_a = []\ndocuments_h = {}\n1.upto(10_000) do |n|\n d = Document.new(n)\n documents_a << d\n documents_h[d.id] = d\nend\nsearchlist = Array.new(1000){ rand(10_000)+1 }\n\nBenchmark.bm(10) do |x|\n x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} }\n x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} }\nend"} {"title": "Recaman's sequence", "language": "Ruby from Kotlin", "task": "The '''Recaman's sequence''' generates Natural numbers.\n\nStarting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* A005132, The On-Line Encyclopedia of Integer Sequences.\n* The Slightly Spooky Recaman Sequence, Numberphile video.\n* Recaman's sequence, on Wikipedia.\n\n", "solution": "require 'set'\n\na = [0]\nused = Set[0]\nused1000 = Set[0]\nfoundDup = false\nn = 1\nwhile n <= 15 or not foundDup or used1000.size < 1001\n nxt = a[n - 1] - n\n if nxt < 1 or used === nxt then\n nxt = nxt + 2 * n\n end\n alreadyUsed = used === nxt\n a << nxt\n if not alreadyUsed then\n used << nxt\n if nxt >= 0 and nxt <= 1000 then\n used1000 << nxt\n end\n end\n if n == 14 then\n print \"The first 15 terms of the Recaman's sequence are \", a, \"\\n\"\n end\n if not foundDup and alreadyUsed then\n print \"The first duplicated term is a[\", n, \"] = \", nxt, \"\\n\"\n foundDup = true\n end\n if used1000.size == 1001 then\n print \"Terms up to a[\", n, \"] are needed to generate 0 to 1000\\n\"\n end\n n = n + 1\nend"} {"title": "Remove lines from a file", "language": "Ruby", "task": "Remove a specific line or a number of lines from a file. \n\nThis should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). \n\nFor the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2\n\nEmpty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. \n\nAn appropriate message should appear if an attempt is made to remove lines beyond the end of the file.\n\n", "solution": "require 'tempfile'\n\ndef remove_lines(filename, start, num)\n tmp = Tempfile.open(filename) do |fp|\n File.foreach(filename) do |line|\n if $. >= start and num > 0\n num -= 1\n else\n fp.puts line\n end\n end\n fp\n end\n puts \"Warning: End of file encountered before all lines removed\" if num > 0\n FileUtils.copy(tmp.path, filename)\n tmp.unlink\nend\n\n# Test code\ndef setup(filename, start, remove)\n puts \"remove #{remove} lines starting at line #{start}\"\n File.open(filename, \"w\") {|fh| (1..5).each {|i| fh.puts \" \"*i + i.to_s}}\n puts \"before:\", File.read(filename)\nend\n\ndef teardown(filename)\n puts \"after:\", File.read(filename)\n puts\n File.unlink(filename)\nend\n\nfilename = \"foobar.txt\"\nstart = 2\n[2, 6].each do |remove|\n setup(filename, start, remove)\n remove_lines(filename, start, remove)\n teardown(filename)\nend"} {"title": "Rep-string", "language": "Ruby", "task": "Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.\n\nFor example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.\n\nNote that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.\n\n\n;Task:\n* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). \n* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.\n* Use the function to indicate the repeating substring if any, in the following:\n\n\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\n\n\n* Show your output on this page.\n\n\n\n", "solution": "ar = %w(1001110011\n 1110111011\n 0010010010\n 1010101010\n 1111111111\n 0100101101\n 0100100\n 101\n 11\n 00\n 1)\n\nar.each do |str|\n rep_pos = (str.size/2).downto(1).find{|pos| str.start_with? str[pos..-1]}\n puts str, rep_pos ? \" \"*rep_pos + str[0, rep_pos] : \"(no repetition)\", \"\"\nend"} {"title": "Repeat", "language": "Ruby", "task": "Write a procedure which accepts as arguments another procedure and a positive integer. \n\nThe latter procedure is executed a number of times equal to the accepted integer.\n\n", "solution": "4.times{ puts \"Example\" } # idiomatic way\n\ndef repeat(proc,num)\n num.times{ proc.call }\nend\n\nrepeat(->{ puts \"Example\" }, 4)"} {"title": "Repunit primes", "language": "Ruby", "task": "portmanteau of the words \"repetition\" and \"unit\", with unit being \"unit value\"... or in laymans terms, '''1'''. So 1, 11, 111, 1111 & 11111 are all repunits.\n\nEvery standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.\n\nIn base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.) \n\nIn base three: 111, 1111111, 1111111111111, etc.\n\n''Repunit primes, by definition, are also [[circular primes]].''\n\nAny repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits ''might'' be prime.\n\n\nRather than expanding the repunit out as a giant list of '''1'''s or converting to base 10, it is common to just list the ''number'' of '''1'''s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.\n\nMany of these sequences exist on OEIS, though they aren't specifically listed as \"repunit prime digits\" sequences. \n\nSome bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.\n\n\n;Task\n\n* For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.\n\n\n;Stretch\n\n* Increase the limit to 2700 (or as high as you have patience for.)\n\n\n;See also\n\n;* Wikipedia: Repunit primes\n;* OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)\n;* OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)\n;* OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)\n;* OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)\n;* OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)\n;* OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)\n;* OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)\n;* OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)\n;* OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)\n;* OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)\n;* OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)\n;* Related task: Circular primes\n\n\n\n", "solution": "require 'prime'\nrequire 'gmp'\n\n(2..16).each do |base|\n res = Prime.each(1000).select {|n| GMP::Z((\"1\" * n).to_i(base)).probab_prime? > 0}\n puts \"Base #{base}: #{res.join(\" \")}\"\nend\n"} {"title": "Reverse words in a string", "language": "Ruby", "task": "Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! would be shown reversed as: Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. \n\nYou may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string (or one just containing spaces) would be the result.\n\n'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. \n\n(You can consider the ten strings as ten lines, and the tokens as words.)\n\n\n;Input data\n\n (ten lines within the box)\n line\n +----------------------------------------+\n 1 | ---------- Ice and Fire ------------ |\n 2 | | <--- a blank line here.\n 3 | fire, in end will world the say Some |\n 4 | ice. in say Some |\n 5 | desire of tasted I've what From |\n 6 | fire. favor who those with hold I |\n 7 | | <--- a blank line here.\n 8 | ... elided paragraph last ... |\n 9 | | <--- a blank line here.\n 10 | Frost Robert ----------------------- |\n +----------------------------------------+\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "puts < fromRoman(r)}"} {"title": "Roman numerals/Encode", "language": "Ruby", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "Symbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' }\nSubtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]\n\ndef roman(num)\n return Symbols[num] if Symbols.has_key?(num)\n Subtractors.each do |cutPoint, subtractor| \n return roman(cutPoint) + roman(num - cutPoint) if num > cutPoint\n return roman(subtractor) + roman(num + subtractor) if num >= cutPoint - subtractor and num < cutPoint\n end\nend\n\n[1990, 2008, 1666].each do |i|\n puts \"%4d => %s\" % [i, roman(i)]\nend"} {"title": "Runge-Kutta method", "language": "Ruby", "task": "Given the example Differential equation:\n:y'(t) = t \\times \\sqrt {y(t)}\nWith initial condition:\n:t_0 = 0 and y_0 = y(t_0) = y(0) = 1\nThis equation has an exact solution:\n:y(t) = \\tfrac{1}{16}(t^2 +4)^2\n\n\n;Task\nDemonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.\n* Solve the given differential equation over the range t = 0 \\ldots 10 with a step value of \\delta t=0.1 (101 total points, the first being given)\n* Print the calculated values of y at whole numbered t's (0.0, 1.0, \\ldots 10.0) along with error as compared to the exact solution.\n\n\n;Method summary\nStarting with a given y_n and t_n calculate:\n:\\delta y_1 = \\delta t\\times y'(t_n, y_n)\\quad\n:\\delta y_2 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_1)\n:\\delta y_3 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_2)\n:\\delta y_4 = \\delta t\\times y'(t_n + \\delta t , y_n + \\delta y_3)\\quad\nthen:\n:y_{n+1} = y_n + \\tfrac{1}{6} (\\delta y_1 + 2\\delta y_2 + 2\\delta y_3 + \\delta y_4)\n:t_{n+1} = t_n + \\delta t\\quad\n\n", "solution": "def calc_rk4(f)\n return ->(t,y,dt){\n ->(dy1 ){\n ->(dy2 ){\n ->(dy3 ){\n ->(dy4 ){ ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 }.call(\n dt * f.call( t + dt , y + dy3 ))}.call(\n dt * f.call( t + dt/2, y + dy2/2 ))}.call(\n dt * f.call( t + dt/2, y + dy1/2 ))}.call(\n dt * f.call( t , y ))}\nend\n\nTIME_MAXIMUM, WHOLE_TOLERANCE = 10.0, 1.0e-5\nT_START, Y_START, DT = 0.0, 1.0, 0.10\n\ndef my_diff_eqn(t,y) ; t * Math.sqrt(y) ; end\ndef my_solution(t ) ; (t**2 + 4)**2 / 16 ; end\ndef find_error(t,y) ; (y - my_solution(t)).abs ; end\ndef is_whole?(t ) ; (t.round - t).abs < WHOLE_TOLERANCE ; end\n\ndy = calc_rk4( ->(t,y){my_diff_eqn(t,y)} )\n\nt, y = T_START, Y_START\nwhile t <= TIME_MAXIMUM\n printf(\"y(%4.1f)\\t= %12.6f \\t error: %12.6e\\n\",t,y,find_error(t,y)) if is_whole?(t)\n t, y = t + DT, y + dy.call(t,y,DT)\nend"} {"title": "Runtime evaluation", "language": "Ruby", "task": "Demonstrate a language's ability for programs to execute code written in the language provided at runtime. \n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].\n\n", "solution": "def first(main_var, main_binding)\n foo = 42\n second [[main_var, main_binding], [\"foo\", binding]]\nend\n\ndef second(args)\n sqr = lambda {|x| x**2}\n deref(args << [\"sqr\", binding])\nend\n\ndef deref(stuff)\n stuff.each do |varname, context|\n puts \"value of #{varname} is #{eval varname, context}\"\n end\nend\n\nhello = \"world\"\nfirst \"hello\", binding"} {"title": "Runtime evaluation/In an environment", "language": "Ruby", "task": "Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.\n\nDo so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": "def bind_x_to_value(x)\n binding\nend\n\ndef eval_with_x(code, a, b)\n eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a))\nend\n\nputs eval_with_x('2 ** x', 3, 5) # Prints \"24\""} {"title": "SHA-1", "language": "Ruby", "task": "'''SHA-1''' or '''SHA1''' is a one-way hash function; \nit computes a 160-bit message digest. \nSHA-1 often appears in security protocols; for example, \nmany HTTPS websites use RSA with SHA-1 to secure their connections. \nBitTorrent uses SHA-1 to verify downloads. \nGit and Mercurial use SHA-1 digests to identify commits.\n\nA US government standard, FIPS 180-1, defines SHA-1.\n\nFind the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.\n\n{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. \nThis is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. \nFor production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}\n", "solution": "require 'stringio'\n\n# Calculates SHA-1 message digest of _string_. Returns binary digest.\n# For hexadecimal digest, use +*sha1(string).unpack('H*')+.\n#--\n# This is a simple, pure-Ruby implementation of SHA-1, following\n# the algorithm in FIPS 180-1.\n#++\ndef sha1(string)\n # functions and constants\n mask = 0xffffffff\n s = proc{|n, x| ((x << n) & mask) | (x >> (32 - n))}\n f = [\n proc {|b, c, d| (b & c) | (b.^(mask) & d)},\n proc {|b, c, d| b ^ c ^ d},\n proc {|b, c, d| (b & c) | (b & d) | (c & d)},\n proc {|b, c, d| b ^ c ^ d},\n ].freeze\n k = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6].freeze\n \n # initial hash\n h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]\n \n bit_len = string.size << 3\n string += \"\\x80\"\n while (string.size % 64) != 56\n string += \"\\0\"\n end\n string = string.force_encoding('ascii-8bit') + [bit_len >> 32, bit_len & mask].pack(\"N2\")\n \n if string.size % 64 != 0\n fail \"failed to pad to correct length\"\n end\n \n io = StringIO.new(string)\n block = \"\"\n \n while io.read(64, block)\n w = block.unpack(\"N16\")\n \n # Process block.\n (16..79).each {|t| w[t] = s[1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]]}\n \n a, b, c, d, e = h\n t = 0\n 4.times do |i|\n 20.times do\n temp = (s[5, a] + f[i][b, c, d] + e + w[t] + k[i]) & mask\n a, b, c, d, e = temp, a, s[30, b], c, d\n t += 1\n end\n end\n \n [a,b,c,d,e].each_with_index {|x,i| h[i] = (h[i] + x) & mask}\n end\n \n h.pack(\"N5\")\nend\n \nif __FILE__ == $0\n # Print some example SHA-1 digests.\n # FIPS 180-1 has correct digests for 'abc' and 'abc...opq'.\n [ 'abc',\n 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',\n 'Rosetta Code',\n ].each {|s| printf(\"%s:\\n %s\\n\", s, *sha1(s).unpack('H*'))}\nend"} {"title": "Sailors, coconuts and a monkey problem", "language": "Ruby", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "def valid?(sailor, nuts)\n sailor.times do\n return false if (nuts % sailor) != 1\n nuts -= 1 + nuts / sailor\n end\n nuts > 0 and nuts % sailor == 0\nend\n\n[5,6].each do |sailor|\n n = sailor\n n += 1 until valid?(sailor, n)\n puts \"\\n#{sailor} sailors => #{n} coconuts\"\n (sailor+1).times do\n div, mod = n.divmod(sailor)\n puts \" #{[n, div, mod]}\"\n n -= 1 + div\n end\nend"} {"title": "Sailors, coconuts and a monkey problem", "language": "Ruby 2.1+", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "def coconuts(sailor)\n sailor.step(by:sailor) do |nuts|\n flag = sailor.times do\n break if nuts % (sailor-1) != 0\n nuts += nuts / (sailor-1) + 1\n end\n return nuts if flag\n end\nend\n\n(2..9).each do |sailor|\n puts \"#{sailor}: #{coconuts(sailor)}\"\nend"} {"title": "Selectively replace multiple instances of a character within a string", "language": "Ruby", "task": "Task\nThis is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.\n\nGiven the string: \"abracadabra\", replace programatically:\n\n* the first 'a' with 'A'\n* the second 'a' with 'B'\n* the fourth 'a' with 'C'\n* the fifth 'a' with 'D'\n* the first 'b' with 'E'\n* the second 'r' with 'F'\n\nNote that there is no replacement for the third 'a', second 'b' or first 'r'.\n\nThe answer should, of course, be : \"AErBcadCbFD\".\n\n\n", "solution": "str = \"abracadabra\"\nrules = [\n [\"a\", 1, \"A\"],\n [\"a\", 2, \"B\"],\n [\"a\", 4, \"C\"],\n [\"a\", 5, \"D\"], \n [\"b\", 1, \"E\"], \n [\"r\", 2, \"F\"]]\n\nindices = Hash.new{[]}\nstr.each_char.with_index{|c, i| indices[c] <<= i}\n\nrules.each{|char, i, to| str[indices[char][i-1]] = to}\n\np str"} {"title": "Self-describing numbers", "language": "Ruby", "task": "{{task}}There are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example, '''2020''' is a four-digit self describing number:\n\n* position 0 has value 2 and there are two 0s in the number;\n* position 1 has value 0 and there are no 1s in the number;\n* position 2 has value 2 and there are two 2s;\n* position 3 has value 0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.\n\n\n;Task Description\n# Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n# As an optional stretch goal - generate and display the set of self-describing numbers.\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-referential sequence]]\n* [[Spelling of ordinal numbers]]\n\n", "solution": "def self_describing?(n)\n digits = n.digits.reverse\n digits.each_with_index.all?{|digit, idx| digits.count(idx) == digit}\nend\n\n3_300_000.times {|n| puts n if self_describing?(n)}"} {"title": "Self-describing numbers", "language": "Ruby from Wren", "task": "{{task}}There are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example, '''2020''' is a four-digit self describing number:\n\n* position 0 has value 2 and there are two 0s in the number;\n* position 1 has value 0 and there are no 1s in the number;\n* position 2 has value 2 and there are two 2s;\n* position 3 has value 0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.\n\n\n;Task Description\n# Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n# As an optional stretch goal - generate and display the set of self-describing numbers.\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-referential sequence]]\n* [[Spelling of ordinal numbers]]\n\n", "solution": "def selfDesc(n)\n ns = n.to_s\n nc = ns.size\n count = Array.new(nc, 0)\n sum = 0\n while n > 0\n d = n % 10\n return false if d >= nc # can't have a digit >= number of digits\n sum += d\n return false if sum > nc\n count[d] += 1\n n /= 10\n end\n # to be self-describing sum of digits must equal number of digits\n return false if sum != nc\n return ns == count.join() # there must always be at least one zero\nend\n\nstart = Time.now\nprint(\"The self-describing numbers are:\")\ni = 10 # self-describing number must end in 0\npw = 10 # power of 10\nfd = 1 # first digit\nsd = 1 # second digit\ndg = 2 # number of digits\nmx = 11 # maximum for current batch\nlim = 9_100_000_001 # sum of digits can't be more than 10\nwhile i < lim\n if selfDesc(i)\n secs = (Time.now - start) #.total_seconds\n print(\"\\n#{i} in #{secs} secs\")\n end\n i += 10\n if i > mx\n fd += 1\n sd -= 1\n if sd >= 0\n i = pw * fd\n else\n pw *= 10\n dg += 1\n i = pw\n fd = 1\n sd = dg - 1\n end\n mx = i + sd * pw / 10\n end\nend\nosecs = (Time.now - start)\nprint(\"\\nTook #{osecs} secs overall\")"} {"title": "Semordnilap", "language": "Ruby", "task": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: ''lager'' and ''regal''\n \n;Task\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\n\n\n", "solution": "dict = File.readlines(\"unixdict.txt\").collect(&:strip)\ni = 0\nres = dict.collect(&:reverse).sort.select do |z| \n i += 1 while z > dict[i] and i < dict.length-1\n z == dict[i] and z < z.reverse\nend\nputs \"There are #{res.length} semordnilaps, of which the following are 5:\"\nres.take(5).each {|z| puts \"#{z} #{z.reverse}\"}"} {"title": "Sequence: nth number with exactly n divisors", "language": "Ruby from Java", "task": "Calculate the sequence where each term an is the nth that has '''n''' divisors.\n\n;Task\n\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n;See also\n\n:*OEIS:A073916\n\n;Related tasks\n\n:*[[Sequence: smallest number greater than previous term with exactly n divisors]]\n:*[[Sequence: smallest number with exactly n divisors]]\n\n", "solution": "def isPrime(n)\n return false if n < 2\n return n == 2 if n % 2 == 0\n return n == 3 if n % 3 == 0\n\n k = 5\n while k * k <= n\n return false if n % k == 0\n k = k + 2\n end\n\n return true\nend\n\ndef getSmallPrimes(numPrimes)\n smallPrimes = [2]\n count = 0\n n = 3\n while count < numPrimes\n if isPrime(n) then\n smallPrimes << n\n count = count + 1\n end\n n = n + 2\n end\n return smallPrimes\nend\n\ndef getDivisorCount(n)\n count = 1\n while n % 2 == 0\n n = (n / 2).floor\n count = count + 1\n end\n\n d = 3\n while d * d <= n\n q = (n / d).floor\n r = n % d\n dc = 0\n while r == 0\n dc = dc + count\n n = q\n q = (n / d).floor\n r = n % d\n end\n count = count + dc\n d = d + 2\n end\n if n != 1 then\n count = 2 * count\n end\n return count\nend\n\nMAX = 15\n@smallPrimes = getSmallPrimes(MAX)\n\ndef OEISA073916(n)\n if isPrime(n) then\n return @smallPrimes[n - 1] ** (n - 1)\n end\n\n count = 0\n result = 0\n i = 1\n while count < n\n if n % 2 == 1 then\n # The solution for an odd (non-prime) term is always a square number\n root = Math.sqrt(i)\n if root * root != i then\n i = i + 1\n next\n end\n end\n if getDivisorCount(i) == n then\n count = count + 1\n result = i\n end\n i = i + 1\n end\n return result\nend\n\nn = 1\nwhile n <= MAX\n print \"A073916(\", n, \") = \", OEISA073916(n), \"\\n\"\n n = n + 1\nend"} {"title": "Sequence: smallest number greater than previous term with exactly n divisors", "language": "Ruby", "task": "Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;See also\n:* OEIS:A069654\n\n\n;Related tasks\n:* [[Sequence: smallest number with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n", "solution": "require 'prime'\n \ndef num_divisors(n)\n n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } \nend\n\nseq = Enumerator.new do |y|\n cur = 0\n (1..).each do |i|\n if num_divisors(i) == cur + 1 then\n y << i\n cur += 1\n end\n end\nend\n\np seq.take(15)\n"} {"title": "Sequence: smallest number with exactly n divisors", "language": "Ruby", "task": "Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "require 'prime'\n \ndef num_divisors(n)\n n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } \nend\n\ndef first_with_num_divs(n)\n (1..).detect{|i| num_divisors(i) == n }\nend\n\np (1..15).map{|n| first_with_num_divs(n) }\n"} {"title": "Set consolidation", "language": "Ruby", "task": "Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n;'''Example 1:'''\n:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n;'''Example 2:'''\n:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n;'''Example 3:'''\n:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n;'''Example 4:'''\n:The consolidation of the five sets:\n::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n:Is the two sets:\n::{A, C, B, D}, and {G, F, I, H, K}\n\n'''See also'''\n* Connected component (graph theory)\n* [[Range consolidation]]\n\n", "solution": "require 'set'\n\ntests = [[[:A,:B], [:C,:D]],\n [[:A,:B], [:B,:D]],\n [[:A,:B], [:C,:D], [:D,:B]],\n [[:H,:I,:K], [:A,:B], [:C,:D], [:D,:B], [:F,:G,:H]]]\ntests.map!{|sets| sets.map(&:to_set)}\n\ntests.each do |sets|\n until sets.combination(2).none?{|a,b| a.merge(b) && sets.delete(b) if a.intersect?(b)}\n end\n p sets\nend"} {"title": "Set of real numbers", "language": "Ruby 1.9.3", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "class Rset\n Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do\n def include?(x)\n (inc_lo ? lo<=x : lo Boolean values\n end\n end\n \n def self.[](lo, hi, inc_hi=true)\n self.new(lo, hi, true, inc_hi)\n end\n \n def self.parse(str)\n raise ArgumentError unless str =~ /(\\[|\\()(.+),(.+)(\\]|\\))/\n b0, lo, hi, b1 = $~.captures # $~ : Regexp.last_match\n lo = Rational(lo)\n lo = lo.numerator if lo.denominator == 1\n hi = Rational(hi)\n hi = hi.numerator if hi.denominator == 1\n self.new(lo, hi, b0=='[', b1==']')\n end\n \n def initialize_copy(obj)\n super\n @sets = @sets.map(&:dup)\n end\n \n def include?(x)\n @sets.any?{|set| set.include?(x)}\n end\n \n def empty?\n @sets.empty?\n end\n \n def union(other)\n sets = (@sets+other.sets).map(&:dup).sort_by{|set| [set.lo, set.hi]}\n work = []\n pre = sets.shift\n sets.each do |post|\n if valid?(pre.hi, post.lo, !pre.inc_hi, !post.inc_lo)\n work << pre\n pre = post\n else\n pre.inc_lo |= post.inc_lo if pre.lo == post.lo\n if pre.hi < post.hi\n pre.hi = post.hi\n pre.inc_hi = post.inc_hi\n elsif pre.hi == post.hi\n pre.inc_hi |= post.inc_hi\n end\n end\n end\n work << pre if pre\n new_Rset(work)\n end\n alias | union\n \n def intersection(other)\n sets = @sets.map(&:dup)\n work = []\n other.sets.each do |oset|\n sets.each do |set|\n if set.hi < oset.lo or oset.hi < set.lo\n # ignore\n elsif oset.lo < set.lo and set.hi < oset.hi\n work << set\n else\n lo = [set.lo, oset.lo].max\n if set.lo == oset.lo\n inc_lo = set.inc_lo && oset.inc_lo\n else\n inc_lo = (set.lo < oset.lo) ? oset.inc_lo : set.inc_lo\n end\n hi = [set.hi, oset.hi].min\n if set.hi == oset.hi\n inc_hi = set.inc_hi && oset.inc_hi\n else\n inc_hi = (set.hi < oset.hi) ? set.inc_hi : oset.inc_hi\n end\n work << Set[lo, hi, inc_lo, inc_hi] if valid?(lo, hi, inc_lo, inc_hi)\n end\n end\n end\n new_Rset(work)\n end\n alias & intersection\n \n def difference(other)\n sets = @sets.map(&:dup)\n other.sets.each do |oset|\n work = []\n sets.each do |set|\n if set.hi < oset.lo or oset.hi < set.lo\n work << set\n elsif oset.lo < set.lo and set.hi < oset.hi\n # delete\n else\n if set.lo < oset.lo\n inc_hi = (set.hi==oset.lo and !set.inc_hi) ? false : !oset.inc_lo\n work << Set[set.lo, oset.lo, set.inc_lo, inc_hi]\n elsif valid?(set.lo, oset.lo, set.inc_lo, !oset.inc_lo)\n work << Set[set.lo, set.lo, true, true]\n end\n if oset.hi < set.hi\n inc_lo = (oset.hi==set.lo and !set.inc_lo) ? false : !oset.inc_hi\n work << Set[oset.hi, set.hi, inc_lo, set.inc_hi]\n elsif valid?(oset.hi, set.hi, !oset.inc_hi, set.inc_hi)\n work << Set[set.hi, set.hi, true, true]\n end\n end\n end\n sets = work\n end\n new_Rset(sets)\n end\n alias - difference\n \n # symmetric difference\n def ^(other)\n (self - other) | (other - self)\n end\n \n def ==(other)\n self.class == other.class and @sets == other.sets\n end\n \n def length\n @sets.inject(0){|len, set| len + set.length}\n end\n \n def to_s\n \"#{self.class}#{@sets.join}\"\n end\n alias inspect to_s\n \n protected\n \n attr_accessor :sets\n \n private\n \n def new_Rset(sets)\n rset = self.class.new # empty set\n rset.sets = sets\n rset\n end\n \n def valid?(lo, hi, inc_lo, inc_hi)\n lo < hi or (lo==hi and inc_lo and inc_hi)\n end\nend\n\ndef Rset(lo, hi, inc_hi=false)\n Rset.new(lo, hi, false, inc_hi)\nend"} {"title": "Set of real numbers", "language": "Ruby 2.1+", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "str, e = \"e = Rset.new\", nil\nputs \"#{str} -> #{eval(str)}\\t\\t# create empty set\"\nstr = \"e.empty?\"\nputs \"#{str} -> #{eval(str)}\"\nputs\n\ninclude Math\nlohi = Enumerator.new do |y|\n t = 1 / sqrt(6)\n 0.step do |n|\n y << [sqrt(12*n+1) * t, sqrt(12*n+5) * t]\n y << [sqrt(12*n+7) * t, sqrt(12*n+11) * t]\n end\nend\n\na = Rset.new\nloop do\n lo, hi = lohi.next\n break if 10 <= lo\n a |= Rset(lo, hi)\nend\na &= Rset(0,10)\n\nb = (0...10).inject(Rset.new){|res,i| res |= Rset(i+1/6r,i+5/6r)}\n\nputs \"a : #{a}\"\nputs \"a.length : #{a.length}\"\nputs \"b : #{b}\"\nputs \"b.length : #{b.length}\"\nputs \"a - b : #{a - b}\"\nputs \"(a-b).length : #{(a-b).length}\""} {"title": "Shoelace formula for polygonal area", "language": "Ruby", "task": "Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:\n\nabs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -\n (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])\n ) / 2\n(Where abs returns the absolute value)\n\n;Task:\nWrite a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:\n (3,4), (5,11), (12,8), (9,5), and (5,6) \n\n\nShow the answer here, on this page.\n\n", "solution": "Point = Struct.new(:x,:y) do\n\n def shoelace(other)\n x * other.y - y * other.x\n end\n\nend\n\nclass Polygon\n\n def initialize(*coords)\n @points = coords.map{|c| Point.new(*c) } \n end\n\n def area\n points = @points + [@points.first]\n points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2)\n end\n\nend\n\nputs Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area # => 30.0\n"} {"title": "Shortest common supersequence", "language": "Ruby from Tcl", "task": "The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task.\n\n\n;;Task:\nGiven two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique.\n\nDemonstrate this by printing s where u = \"abcbdab\" and v = \"bdcaba\".\n\n\n\n;Also see:\n* Wikipedia: shortest common supersequence \n\n", "solution": "require 'lcs'\n\ndef scs(u, v)\n lcs = lcs(u, v)\n u, v = u.dup, v.dup\n scs = \"\"\n # Iterate over the characters until LCS processed\n until lcs.empty?\n if u[0]==lcs[0] and v[0]==lcs[0]\n # Part of the LCS, so consume from all strings\n scs << lcs.slice!(0)\n u.slice!(0)\n v.slice!(0)\n elsif u[0]==lcs[0]\n # char of u = char of LCS, but char of LCS v doesn't so consume just that\n scs << v.slice!(0)\n else\n # char of u != char of LCS, so consume just that\n scs << u.slice!(0)\n end\n end\n # append remaining characters, which are not in common\n scs + u + v\nend\n\nu = \"abcbdab\"\nv = \"bdcaba\"\nputs \"SCS(#{u}, #{v}) = #{scs(u, v)}\""} {"title": "Show ASCII table", "language": "Ruby", "task": "Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.\n\n\n\n", "solution": "chars = (32..127).map do |ord|\n k = case ord\n when 32 then \"\u2420\"\n when 127 then \"\u2421\"\n else ord.chr \n end\n \"#{ord.to_s.ljust(3)}: #{k}\"\nend\n \nchars.each_slice(chars.size/6).to_a.transpose.each{|s| puts s.join(\" \")}"} {"title": "Show the epoch", "language": "Ruby", "task": "Choose popular date libraries used by your language and show the epoch those libraries use. \n\nA demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. \n\nFor consistency's sake, show the date in UTC time where possible.\n\n\n;Related task:\n* [[Date format]]\n\n", "solution": "require \"date\"\nDate.new # => # \n"} {"title": "Smallest number k such that k+2^m is composite for all m less than k", "language": "Ruby", "task": "Generate the sequence of numbers '''a(k)''', where each '''k''' is the smallest positive integer such that '''k + 2m''' is composite for every positive integer '''m''' less than '''k'''.\n\n\n;For example\n\nSuppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. \n\nIs 7 + 21 (9) prime? False\n\nIs 7 + 22 (11) prime? True\n\nSo 7 is not an element of this sequence.\n\nIt is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite.\n\n\n;Task \n\nFind and display, here on this page, the first '''5''' elements of this sequence.\n\n\n;See also\n\nOEIS:A033919 - Odd k for which k+2^m is composite for all m < k\n\n\n", "solution": "require 'openssl'\n\na = (1..).step(2).lazy.select do |k|\n next if k == 1\n (1..(k-1)).none? {|m| OpenSSL::BN.new(k+(2**m)).prime?}\nend\np a.first 5"} {"title": "Smith numbers", "language": "Ruby", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as ''joke'' numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: [Smith number].\n* from MathWorld: [Smith number]. \n* from OEIS A6753: [OEIS sequence A6753].\n* from OEIS A104170: [Number of Smith numbers below 10^n]. \n* from The Prime pages: [Smith numbers].\n\n", "solution": "require \"prime\"\n \nclass Integer\n \n def smith?\n return false if prime?\n digits.sum == prime_division.map{|pr,n| pr.digits.sum * n}.sum\n end\n \nend\n \nn = 10_000\nres = 1.upto(n).select(&:smith?)\n \nputs \"#{res.size} smith numbers below #{n}:\n#{res.first(5).join(\", \")},... #{res.last(5).join(\", \")}\""} {"title": "Solve a Hidato puzzle", "language": "Ruby", "task": "The task is to write a program which solves Hidato (aka Hidoku) puzzles.\n\nThe rules are:\n* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.\n** The grid is not necessarily rectangular.\n** The grid may have holes in it.\n** The grid is always connected.\n** The number \"1\" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.\n** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.\n* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from \"1\" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).\n** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.\n** A square may only contain one number.\n* In a proper Hidato puzzle, the solution is unique.\n\nFor example the following problem\nSample Hidato problem, from Wikipedia\n\nhas the following solution, with path marked on it:\n\nSolution to sample Hidato problem\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]];\n\n", "solution": "# Solve a Hidato Puzzle\n#\nclass Hidato\n Cell = Struct.new(:value, :used, :adj)\n ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]\n \n def initialize(board, pout=true)\n @board = []\n board.each_line do |line|\n @board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil]\n end\n @board << [] # frame (Sentinel value : nil)\n @board.each_with_index do |row, x|\n row.each_with_index do |cell, y|\n if cell\n @sx, @sy = x, y if cell.value==1 # start position\n cell.adj = ADJUST.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]}\n end\n end\n end\n @xmax = @board.size - 1\n @ymax = @board.map(&:size).max - 1\n @end = @board.flatten.compact.size\n puts to_s('Problem:') if pout\n end\n \n def solve\n @zbl = Array.new(@end+1, false)\n @board.flatten.compact.each{|cell| @zbl[cell.value] = true}\n puts (try(@board[@sx][@sy], 1) ? to_s('Solution:') : \"No solution\")\n end\n \n def try(cell, seq_num)\n return true if seq_num > @end\n return false if cell.used\n value = cell.value\n return false if value > 0 and value != seq_num\n return false if value == 0 and @zbl[seq_num]\n cell.used = true\n cell.adj.each do |x, y|\n if try(@board[x][y], seq_num+1)\n cell.value = seq_num\n return true\n end\n end\n cell.used = false\n end\n \n def to_s(msg=nil)\n str = (0...@xmax).map do |x|\n (0...@ymax).map{|y| \"%3s\" % ((c=@board[x][y]) ? c.value : c)}.join\n end\n (msg ? [msg] : []) + str + [\"\"]\n end\nend"} {"title": "Solve a Holy Knight's tour", "language": "Ruby", "task": "Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "require 'HLPsolver'\n\nADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]]\n\nboardy = < ####\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> ######\n:: (Aiming to use just three spark levels)\n\n:: It may be helpful to include these cases in output tests.\n* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.\n\n", "solution": "bar = ('\u2581'..'\u2588').to_a \nloop {print 'Numbers please separated by space/commas: '\n numbers = gets.split(/[\\s,]+/).map(&:to_f)\n min, max = numbers.minmax\n puts \"min: %5f; max: %5f\"% [min, max]\n div = (max - min) / (bar.size - 1)\n puts min == max ? bar.last*numbers.size : numbers.map{|num| bar[((num - min) / div).to_i]}.join\n}"} {"title": "Sphenic numbers", "language": "Ruby", "task": "Definitions\nA '''sphenic number''' is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below).\n\nFor the purposes of this task, a '''sphenic triplet''' is a group of three sphenic numbers which are consecutive. \n\nNote that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct.\n\n;Examples\n30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one.\n\n[1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers.\n\n;Task\nCalculate and show here:\n\n1. All sphenic numbers less than 1,000.\n\n2. All sphenic triplets less than 10,000.\n\n;Stretch\n\n3. How many sphenic numbers are there less than 1 million?\n\n4. How many sphenic triplets are there less than 1 million?\n\n5. What is the 200,000th sphenic number and its 3 prime factors?\n\n6. What is the 5,000th sphenic triplet?\n\nHint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6.\n\n;References\n\n* Wikipedia: Sphenic number\n* OEIS:A007304 - Sphenic numbers\n* OEIS:A165936 - Sphenic triplets (in effect)\n\n;Related tasks\n* [[Almost prime]]\n* [[Square-free integers]]\n\n", "solution": "require 'prime'\n\nclass Integer\n def sphenic? = prime_division.map(&:last) == [1, 1, 1]\nend\n\nsphenics = (1..).lazy.select(&:sphenic?)\n\nn = 1000\nputs \"Sphenic numbers less than #{n}:\"\np sphenics.take_while{|s| s < n}.to_a\n\nn = 10_000\nputs \"\\nSphenic triplets less than #{n}:\"\nsps = sphenics.take_while{|s| s < n}.to_a\nsps.each_cons(3).select{|a, b, c| a + 2 == c}.each{|ar| p ar}\n\nn = 1_000_000\nsphenics_below10E6 = sphenics.take_while{|s| s < n}.to_a\nputs \"\\nThere are #{sphenics_below10E6.size} sphenic numbers below #{n}.\"\ntarget = sphenics_below10E6[200_000-1]\nputs \"\\nThe 200000th sphenic number is #{target} with factors #{target.prime_division.map(&:first)}.\"\ntriplets = sphenics_below10E6.each_cons(3).select{|a,b,c|a+2 == c}\nputs \"\\nThe 5000th sphenic triplet is #{triplets[4999]}.\""} {"title": "Split a character string based on change of character", "language": "Ruby", "task": "Split a (character) string into comma (plus a blank) delimited\nstrings based on a change of character (left to right).\n\nShow the output here (use the 1st example below).\n\n\nBlanks should be treated as any other character (except\nthey are problematic to display clearly). The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "def split(str)\n puts \" input string: #{str}\"\n s = str.chars.chunk(&:itself).map{|_,a| a.join}.join(\", \")\n puts \"output string: #{s}\"\n s\nend\n\nsplit(\"gHHH5YY++///\\\\\")"} {"title": "Square-free integers", "language": "Ruby", "task": "Write a function to test if a number is ''square-free''.\n\n\nA ''square-free'' is an integer which is divisible by no perfect square other\nthan '''1''' (unity).\n\nFor this task, only positive square-free numbers will be used.\n\n\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n::* '''1''' ---> '''145''' (inclusive)\n::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)\n\n\n(One trillion = 1,000,000,000,000)\n\n\nShow here (on this page) the count of square-free integers from:\n::* '''1''' ---> one hundred (inclusive)\n::* '''1''' ---> one thousand (inclusive)\n::* '''1''' ---> ten thousand (inclusive)\n::* '''1''' ---> one hundred thousand (inclusive)\n::* '''1''' ---> one million (inclusive)\n\n\n;See also:\n:* the Wikipedia entry: square-free integer\n\n", "solution": "require \"prime\"\n\nclass Integer\n def square_free?\n prime_division.none?{|pr, exp| exp > 1}\n end\nend\n\nputs (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(\" \")}\nputs\n\nm = 10**12\nputs (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(\" \")}\nputs\n\nmarkers = [100, 1000, 10_000, 100_000, 1_000_000]\ncount = 0\n(1..1_000_000).each do |n|\n count += 1 if n.square_free?\n puts \"#{count} square-frees upto #{n}\" if markers.include?(n)\nend \n"} {"title": "Square but not cube", "language": "Ruby", "task": "Show the first '''30''' positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.\n\n", "solution": "#!/usr/bin/env ruby\n\nclass PowIt\n\t:next\n\t\n\tdef initialize\n\t\t@next = 1;\n\tend\nend\n\nclass SquareIt < PowIt\n\tdef next\n\t\tresult = @next ** 2\n\t\t@next += 1\n\t\treturn result\n\tend\nend\n\nclass CubeIt < PowIt\n\tdef next\n\t\tresult = @next ** 3\n\t\t@next += 1\n\t\treturn result\n\tend\nend\n\nsquares = []\nhexponents = []\n\nsquit = SquareIt.new\ncuit = CubeIt.new\n\ns = squit.next\nc = cuit.next\n\nwhile (squares.length < 30 || hexponents.length < 3)\n\tif s < c\n\t\tsquares.push(s) if squares.length < 30\n\t\ts = squit.next\n\telsif s == c\n\t\thexponents.push(s) if hexponents.length < 3\n\t\ts = squit.next\n\t\tc = cuit.next\n\telse\n\t\tc = cuit.next\n\tend\nend\n\nputs \"Squares:\"\nputs squares.join(\" \")\n\nputs \"Square-and-cubes:\"\nputs hexponents.join(\" \")"} {"title": "Stair-climbing puzzle", "language": "Ruby", "task": "From Chung-Chieh Shan (LtU):\n\nYour stair-climbing robot has a very simple low-level API: the \"step\" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The \"step\" function detects what happens and returns a boolean flag: true on success, false on failure. \n\nWrite a function \"step_up\" that climbs one step up [from the initial position] (by repeating \"step\" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make \"step_up\"? Can you avoid using variables (even immutable ones) and numbers?\n\nHere's a pseudo-code of a simple recursive solution without using variables:\n\nfunc step_up()\n{\n if not step() {\n step_up();\n step_up();\n }\n}\n\nInductive proof that step_up() steps up one step, if it terminates:\n* Base case (if the step() call returns true): it stepped up one step. QED\n* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED\n\n\nThe second (tail) recursion above can be turned into an iteration, as follows:\n\nfunc step_up()\n{\n while not step() {\n step_up();\n }\n}\n\n", "solution": "def step_up\n start_position = $position\n step until ($position == start_position + 1)\nend\n\n# assumptions about the step function:\n# - it maintains the current position of the robot \"as a side effect\"\n# - the robot is equally likely to step back as to step up\ndef step\n if rand < 0.5\n $position -= 1\n p \"fall (#$position)\" if $DEBUG\n return false\n else\n $position += 1\n p \"rise (#$position)\" if $DEBUG\n return true\n end\nend\n\n$position = 0\nstep_up"} {"title": "Statistics/Normal distribution", "language": "Ruby 2.7", "task": "The derive normally distributed random numbers from a uniform generator.\n\n\n;The task:\n# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.\n# Mention any native language support for the generation of normally distributed random numbers.\n\n\n;Reference:\n* You may refer to code in [[Statistics/Basic]] if available.\n\n", "solution": "# Class to implement a Normal distribution, generated from a Uniform distribution.\n# Uses the Marsaglia polar method.\n\nclass NormalFromUniform\n # Initialize an instance.\n def initialize()\n @next = nil\n end\n # Generate and return the next Normal distribution value.\n def rand()\n if @next\n retval, @next = @next, nil\n return retval\n else\n u = v = s = nil\n loop do\n u = Random.rand(-1.0..1.0)\n v = Random.rand(-1.0..1.0)\n s = u**2 + v**2\n break if (s > 0.0) && (s <= 1.0)\n end\n f = Math.sqrt(-2.0 * Math.log(s) / s)\n @next = v * f\n return u * f\n end\n end\nend"} {"title": "Stern-Brocot sequence", "language": "Ruby 2.1", "task": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].\n\n# The first and second members of the sequence are both 1:\n#* 1, 1\n# Start by considering the second member of the sequence\n# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n#* 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* --- Expanding another loop we get: ---\n#*\n# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n#* 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1, 3, 2\n# Consider the next member of the series, (the fourth member i.e. 1)\n\n\n;The task is to:\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\n\n;Related tasks:\n:* [[Fusc sequence]].\n:* [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "def sb\n return enum_for :sb unless block_given?\n a=[1,1]\n 0.step do |i|\n yield a[i]\n a << a[i]+a[i+1] << a[i+1]\n end\nend\n\nputs \"First 15: #{sb.first(15)}\"\n\n[*1..10,100].each do |n| \n puts \"#{n} first appears at #{sb.find_index(n)+1}.\"\nend\n\nif sb.take(1000).each_cons(2).all? { |a,b| a.gcd(b) == 1 }\n puts \"All GCD's are 1\"\nelse\n puts \"Whoops, not all GCD's are 1!\"\nend"} {"title": "Stirling numbers of the first kind", "language": "Ruby from D", "task": "Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number\nof cycles (counting fixed points as cycles of length one).\n\nThey may be defined directly to be the number of permutations of '''n'''\nelements with '''k''' disjoint cycles.\n\nStirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.\n\nDepending on the application, Stirling numbers of the first kind may be \"signed\"\nor \"unsigned\". Signed Stirling numbers of the first kind arise when the\npolynomial expansion is expressed in terms of falling factorials; unsigned when\nexpressed in terms of rising factorials. The only substantial difference is that,\nfor signed Stirling numbers of the first kind, values of S1(n, k) are negative\nwhen n + k is odd.\n\nStirling numbers of the first kind follow the simple identities:\n\n S1(0, 0) = 1\n S1(n, 0) = 0 if n > 0\n S1(n, k) = 0 if k > n\n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned\n ''or''\n S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the first kind'''. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, '''S1(n, k)''', up to '''S1(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S1(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the first kind'''\n:* '''OEIS:A008275 - Signed Stirling numbers of the first kind'''\n:* '''OEIS:A130534 - Unsigned Stirling numbers of the first kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the second kind'''\n:* '''Lah numbers'''\n\n\n", "solution": "$cache = {}\ndef sterling1(n, k)\n if n == 0 and k == 0 then\n return 1\n end\n if n > 0 and k == 0 then\n return 0\n end\n if k > n then\n return 0\n end\n key = [n, k]\n if $cache[key] then\n return $cache[key]\n end\n value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)\n $cache[key] = value\n return value\nend\n\nMAX = 12\ndef main\n print \"Unsigned Stirling numbers of the first kind:\\n\"\n print \"n/k\"\n for n in 0 .. MAX\n print \"%10d\" % [n]\n end\n print \"\\n\"\n\n for n in 0 .. MAX\n print \"%-3d\" % [n]\n for k in 0 .. n\n print \"%10d\" % [sterling1(n, k)]\n end\n print \"\\n\"\n end\n\n print \"The maximum value of S1(100, k) =\\n\"\n previous = 0\n for k in 1 .. 100\n current = sterling1(100, k)\n if previous < current then\n previous = current\n else\n print previous, \"\\n\"\n print \"(%d digits, k = %d)\\n\" % [previous.to_s.length, k - 1]\n break\n end\n end\nend\n\nmain()"} {"title": "Stirling numbers of the second kind", "language": "Ruby", "task": "Stirling numbers of the second kind, or Stirling partition numbers, are the\nnumber of ways to partition a set of n objects into k non-empty subsets. They are\nclosely related to [[Bell numbers]], and may be derived from them.\n\n\nStirling numbers of the second kind obey the recurrence relation:\n\n S2(n, 0) and S2(0, k) = 0 # for n, k > 0\n S2(n, n) = 1\n S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)\n\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the second kind'''. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, '''S2(n, k)''', up to '''S2(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S2(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the second kind'''\n:* '''OEIS:A008277 - Stirling numbers of the second kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Bell numbers'''\n:* '''Lah numbers'''\n\n\n", "solution": "@memo = {}\n\ndef sterling2(n, k)\n key = [n,k]\n return @memo[key] if @memo.key?(key)\n return 1 if n.zero? and k.zero?\n return 0 if n.zero? or k.zero?\n return 1 if n == k\n return 0 if k > n\n res = k * sterling2(n-1, k) + sterling2(n - 1, k-1)\n @memo[key] = res\nend\n\nr = (0..12)\nputs \"Sterling2 numbers:\"\nputs \"n/k #{r.map{|n| \"%11d\" % n}.join}\"\n \nr.each do |row|\n print \"%-4s\" % row\n puts \"#{(0..row).map{|col| \"%11d\" % sterling2(row, col)}.join}\"\nend\n \nputs \"\\nMaximum value from the sterling2(100, k)\";\nputs (1..100).map{|a| sterling2(100,a)}.max\n"} {"title": "Stream merge", "language": "Ruby", "task": " 2-stream merge\n: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.\n: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.\n\n; ''N''-stream merge\n: The same as above, but reading from ''N'' sources.\n: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].\n\n\nAssume streams are very big. You must not suck them whole in the memory, but read them as streams.\n\n", "solution": "def stream_merge(*files)\n fio = files.map{|fname| open(fname)}\n merge(fio.map{|io| [io, io.gets]})\nend\n\ndef merge(fdata)\n until fdata.empty?\n io, min = fdata.min_by{|_,data| data}\n puts min\n if (next_data = io.gets).nil?\n io.close\n fdata.delete([io, min])\n else\n i = fdata.index{|x,_| x == io}\n fdata[i] = [io, next_data]\n end\n end\nend\n\nfiles = %w(temp1.dat temp2.dat temp3.dat)\nfiles.each do |fname|\n data = IO.read(fname).gsub(\"\\n\", \" \")\n puts \"#{fname}: #{data}\"\nend\nstream_merge(*files)"} {"title": "Strip control codes and extended characters from a string", "language": "Ruby", "task": "Strip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* a string with control codes stripped (but extended characters not stripped)\n:* a string with control codes and extended characters stripped\n\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127. \n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\n\n", "solution": "class String\n def strip_control_characters()\n chars.each_with_object(\"\") do |char, str|\n str << char unless char.ascii_only? and (char.ord < 32 or char.ord == 127)\n end\n end\n \n def strip_control_and_extended_characters()\n chars.each_with_object(\"\") do |char, str|\n str << char if char.ascii_only? and char.ord.between?(32,126)\n end\n end\nend\n\np s = \"\\ba\\x00b\\n\\rc\\fd\\xc3\\x7ffoo\"\np s.strip_control_characters\np s.strip_control_and_extended_characters"} {"title": "Subleq", "language": "Ruby", "task": "One-Instruction Set Computer (OISC). \n\nIt is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. \n\n;Task\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:\n::::* simple numeric values \n::::* memory addresses \n::::* characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine. \n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.\n:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.\n:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.\n:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.\n:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.\n:# If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).\n\nFor purposes of this task, show the output of your solution when fed the below \"Hello, world!\" program. \n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\nstart:\n 0f 11 ff subleq (zero), (message), -1\n 11 ff ff subleq (message), -1, -1 ; output character at message\n 10 01 ff subleq (neg1), (start+1), -1\n 10 03 ff subleq (neg1), (start+3), -1\n 0f 0f 00 subleq (zero), (zero), start\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n\n", "solution": "class Computer\n def initialize program\n @memory = program.map &:to_i\n @instruction_pointer = 0\n end\n\n def step\n return nil if @instruction_pointer < 0\n\n a, b, c = @memory[@instruction_pointer .. @instruction_pointer + 2]\n @instruction_pointer += 3\n\n if a == -1\n b = readchar\n elsif b == -1\n writechar @memory[a]\n else\n difference = @memory[b] -= @memory[a]\n @instruction_pointer = c if difference <= 0\n end\n\n @instruction_pointer\n end\n\n def run\n current_pointer = @instruction_pointer\n current_pointer = step while current_pointer >= 0\n end\n\n private\n\n def readchar\n gets[0].ord\n end\n\n def writechar code_point\n print code_point.chr\n end\nend\n\nsubleq = Computer.new ARGV\n\nsubleq.run"} {"title": "Substring/Top and tail", "language": "Ruby", "task": "The task is to demonstrate how to remove the first and last characters from a string. \n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. \n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. \n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n", "solution": "puts \"knight\"[1..-1] # strip first character\nputs \"socks\"[0..-2] # strip last character\nputs \"socks\".chop # alternate way to strip last character\nputs \"brooms\"[1..-2] # strip both first and last characters\nputs \"\u4e0e\u4eca\u4ee4\"[1..-2] # => \u4eca"} {"title": "Sum and product puzzle", "language": "Ruby from D", "task": "* Wikipedia: Sum and Product Puzzle\n\n", "solution": "def add(x,y) x + y end\ndef mul(x,y) x * y end\n\ndef sumEq(s,p) s.select{|q| add(*p) == add(*q)} end\ndef mulEq(s,p) s.select{|q| mul(*p) == mul(*q)} end\n\ns1 = (a = *2...100).product(a).select{|x,y| x 0\n term += digit_count[d].to_s + d.to_s\n end\n end\n term = term.to_i\n $cache[n] = [n] + selfReferentialSequence_cached(term, [n] + seen)\nend\n\nlimit = 1_000_000\nmax_len = 0\nmax_vals = []\n\n1.upto(limit - 1) do |n| \n seq = selfReferentialSequence_cached(n)\n if seq.length > max_len\n max_len = seq.length\n max_vals = [n]\n elsif seq.length == max_len\n max_vals << n\n end\nend\n\nputs \"values: #{max_vals.inspect}\"\nputs \"iterations: #{max_len}\"\nputs \"sequence:\"\nselfReferentialSequence_cached(max_vals[0]).each_with_index do |val, idx| \n puts \"%2d %d\" % [idx + 1, val]\nend"} {"title": "Summarize primes", "language": "Ruby from C++", "task": "Considering in order of length, n, all sequences of consecutive\nprimes, p, from 2 onwards, where p < 1000 and n>0, select those\nsequences whose sum is prime, and for these display the length of the\nsequence, the last item in the sequence, and the sum.\n\n", "solution": "def isPrime(n)\n if n < 2 then\n return false\n end\n\n if n % 2 == 0 then\n return n == 2\n end\n if n % 3 == 0 then\n return n == 3\n end\n\n i = 5\n while i * i <= n\n if n % i == 0 then\n return false\n end\n i += 2\n\n if n % i == 0 then\n return false\n end\n i += 4\n end\n return true\nend\n\nSTART = 1\nSTOP = 1000\n\nsum = 0\ncount = 0\nsc = 0\n\nfor p in START .. STOP\n if isPrime(p) then\n count += 1\n sum += p\n if isPrime(sum) then\n print \"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\" % [count, p, sum]\n sc += 1\n end\n end\nend\nprint \"There are %d summerized primes in [%d, %d]\\n\" % [sc, START, STOP]"} {"title": "Super-d numbers", "language": "Ruby", "task": "A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where\n 2 <= d <= 9\nFor instance, 753 is a super-3 number because 3 x 7533 = 1280873331.\n\n\n'''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers.\n\n\n;Extra credit:\n:* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional).\n\n\n;See also:\n:* Wolfram MathWorld - Super-d Number.\n:* OEIS: A014569 - Super-3 Numbers.\n\n", "solution": "(2..8).each do |d|\n rep = d.to_s * d\n print \"#{d}: \"\n puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(\", \")\nend\n"} {"title": "Superpermutation minimisation", "language": "Ruby", "task": "A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.\n\nFor example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. \nThe permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.\n\nA too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.\n\nA little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.\n\nThe \"too obvious\" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.\n\nShow descriptions and comparisons of algorithms used here, and select the \"Best\" algorithm as being the one generating shorter superpermutations.\n\nThe problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.\n\n\n\n\n;Reference:\n* The Minimal Superpermutation Problem. by Nathaniel Johnston.\n* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.\n* Superpermutations - Numberphile. A video\n* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.\n* New Superpermutations Discovered! Standupmaths & Numberphile.\n\n", "solution": "#A straight forward implementation of N. Johnston's algorithm. I prefer to look at this as 2n+1 where\n#the second n is first n reversed, and the 1 is always the second symbol. This algorithm will generate\n#just the left half of the result by setting l to [1,2] and looping from 3 to 6. For the purpose of\n#this task I am going to start from an empty array and generate the whole strings using just the \n#rules.\n#\n#Nigel Galloway: December 16th., 2014\n#\nl = []\n(1..6).each{|e|\n a, i = [], e-2\n (0..l.length-e+1).each{|g|\n if not (n = l[g..g+e-2]).uniq!\n a.concat(n[(a[0]? i : 0)..-1]).push(e).concat(n)\n i = e-2\n else\n i -= 1\n end\n }\n a.each{|n| print n}; puts \"\\n\\n\"\n l = a\n}"} {"title": "Sylvester's sequence", "language": "Ruby", "task": "{{Wikipedia|Sylvester's sequence}}\n\n\nIn number theory, '''Sylvester's sequence''' is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.\n\nIts values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to '''1''' more rapidly than any other series of unit fractions with the same number of terms. \n\nFurther, the sum of the first '''k''' terms of the infinite series of reciprocals provides the closest possible underestimate of '''1''' by any k-term Egyptian fraction.\n\n\n;Task:\n* Write a routine (function, procedure, generator, whatever) to calculate '''Sylvester's sequence'''.\n* Use that routine to show the values of the first '''10''' elements in the sequence.\n* Show the sum of the reciprocals of the first '''10''' elements on the sequence, ideally as an exact fraction.\n\n\n;Related tasks:\n* [[Egyptian fractions]]\n* [[Harmonic series]]\n\n\n;See also: \n* OEIS A000058 - Sylvester's sequence\n\n", "solution": "def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }\n \n(0..9).each {|n| puts \"#{n}: #{sylvester n}\" }\nputs \"\nSum of reciprocals of first 10 terms:\n#{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }\"\n"} {"title": "Tau function", "language": "Ruby", "task": "Given a positive integer, count the number of its positive divisors.\n\n\n;Task\nShow the result for the first '''100''' positive integers.\n\n\n;Related task\n* [[Tau number]]\n\n", "solution": "require 'prime'\n\ndef tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1}\n\n(1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}\n"} {"title": "Teacup rim text", "language": "Ruby", "task": "On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*). \n\nIt occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: unixdict.txt. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.) \n\nHaving listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc. \n\nThe words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "lists = [\"unixdict.txt\", \"wordlist.10000\", \"woordenlijst.txt\"]\n\nlists.each do |list|\n words = open(list).readlines( chomp: true).reject{|w| w.size < 3 }\n grouped_by_size = words.group_by(&:size)\n tea_words = words.filter_map do |word|\n chars = word.chars\n next unless chars.none?{|c| c < chars.first }\n next if chars.uniq.size == 1\n rotations = word.size.times.map {|i| chars.rotate(i).join }\n rotations if rotations.all?{|rot| grouped_by_size[rot.size].include? rot }\n end\n puts \"\", list + \":\"\n tea_words.uniq(&:to_set).each{|ar| puts ar.join(\", \") }\nend\n"} {"title": "Temperature conversion", "language": "Ruby", "task": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: \nRankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n \n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\n\n;Task\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. \n\n\n;Example:\n\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n\n", "solution": "module TempConvert\n\n FROM_TEMP_SCALE_TO_K = \n {'kelvin' => lambda{|t| t},\n 'celsius' => lambda{|t| t + 273.15},\n 'fahrenheit' => lambda{|t| (t + 459.67) * 5/9.0},\n 'rankine' => lambda{|t| t * 5/9.0},\n 'delisle' => lambda{|t| 373.15 - t * 2/3.0},\n 'newton' => lambda{|t| t * 100/33.0 + 273.15},\n 'reaumur' => lambda{|t| t * 5/4.0 + 273.15},\n 'roemer' => lambda{|t| (t - 7.5) * 40/21.0 + 273.15}}\n\n TO_TEMP_SCALE_FROM_K = \n {'kelvin' => lambda{|t| t},\n 'celsius' => lambda{|t| t - 273.15},\n 'fahrenheit' => lambda{|t| t * 9/5.0 - 459.67},\n 'rankine' => lambda{|t| t * 9/5.0},\n 'delisle' => lambda{|t| (373.15 - t) * 3/2.0},\n 'newton' => lambda{|t| (t - 273.15) * 33/100.0},\n 'reaumur' => lambda{|t| (t - 273.15) * 4/5.0},\n 'roemer' => lambda{|t| (t - 273.15) * 21/40.0 + 7.5}}\n \n SUPPORTED_SCALES = FROM_TEMP_SCALE_TO_K.keys.join('|')\n\n def self.method_missing(meth, *args, &block)\n if valid_temperature_conversion?(meth) then\n convert_temperature(meth, *args)\n else\n super\n end\n end\n\n def self.respond_to_missing?(meth, include_private = false)\n valid_temperature_conversion?(meth) || super\n end\n \n def self.valid_temperature_conversion?(meth)\n !!(meth.to_s =~ /(#{SUPPORTED_SCALES})_to_(#{SUPPORTED_SCALES})/) \n end\n \n def self.convert_temperature(meth, temp)\n from_scale, to_scale = meth.to_s.split(\"_to_\")\n return temp.to_f if from_scale == to_scale # no kelvin roundtrip \n TO_TEMP_SCALE_FROM_K[to_scale].call(FROM_TEMP_SCALE_TO_K[from_scale].call(temp)).round(2)\n end\n \nend"} {"title": "Terminal control/Unicode output", "language": "Ruby", "task": "The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.\n\nNote that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.\n\n", "solution": "#encoding: UTF-8 # superfluous in Ruby >1.9.3\n\nif ENV.values_at(\"LC_ALL\",\"LC_CTYPE\",\"LANG\").compact.first.include?(\"UTF-8\")\n puts \"\u25b3\"\nelse\n raise \"Terminal can't handle UTF-8\"\nend\n"} {"title": "Test integerness", "language": "Ruby", "task": "{| class=\"wikitable\"\n|-\n! colspan=2 | Input\n! colspan=2 | Output\n! rowspan=2 | Comment\n|-\n! Type\n! Value\n! exact\n! tolerance = 0.00001\n|-\n| rowspan=3 | decimal\n| 25.000000\n| colspan=2 | true\n| \n|-\n| 24.999999\n| false\n| true\n| \n|-\n| 25.000100\n| colspan=2 | false\n| \n|-\n| rowspan=4 | floating-point\n| -2.1e120\n| colspan=2 | true\n| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.\n|-\n| -5e-2\n| colspan=2 | false\n| \n|-\n| NaN\n| colspan=2 | false\n| \n|-\n| Inf\n| colspan=2 | false\n| This one is debatable. If your code considers it an integer, that's okay too.\n|-\n| rowspan=2 | complex\n| 5.0+0.0i\n| colspan=2 | true\n| \n|-\n| 5-5i\n| colspan=2 | false\n| \n|}\n\n(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)\n\n\n", "solution": "class Numeric\n def to_i?\n self == self.to_i rescue false\n end\nend\n \n# Demo\nar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, # Floats\n Float::NAN, Float::INFINITY, # more Floats\n 2r, 2.5r, # Rationals \n 2+0i, 2+0.0i, 5-5i] # Complexes\n \nar.each{|num| puts \"#{num} integer? #{num.to_i?}\" }\n"} {"title": "Textonyms", "language": "Ruby", "task": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n\n;Task:\nWrite a program that finds textonyms in a list of words such as \n[[Textonyms/wordlist]] or \nunixdict.txt.\n\nThe task should produce a report:\n\n There are #{0} words in #{1} which can be represented by the digit key mapping.\n They require #{2} digit combinations to represent them.\n #{3} digit combinations represent Textonyms.\n\nWhere:\n #{0} is the number of words in the list which can be represented by the digit key mapping.\n #{1} is the URL of the wordlist being used.\n #{2} is the number of digit combinations required to represent the words in #{0}.\n #{3} is the number of #{2} which represent more than one word.\n\nAt your discretion show a couple of examples of your solution displaying Textonyms. \n\nE.G.:\n\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n\n;Extra credit:\nUse a word list and keypad mapping other than English.\n\n\n\n", "solution": "CHARS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nNUMS = \"22233344455566677778889999\" * 2\ndict = \"unixdict.txt\"\n\ntextonyms = File.open(dict){|f| f.map(&:chomp).group_by {|word| word.tr(CHARS, NUMS) } }\n\nputs \"There are #{File.readlines(dict).size} words in #{dict} which can be represented by the digit key mapping.\nThey require #{textonyms.size} digit combinations to represent them.\n#{textonyms.count{|_,v| v.size > 1}} digit combinations represent Textonyms.\"\n\nputs \"\\n25287876746242: #{textonyms[\"25287876746242\"].join(\", \")}\"\n"} {"title": "The Name Game", "language": "Ruby 2.7.1", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "#!/usr/bin/env ruby\n\ndef print_verse(name)\n first_letter_and_consonants_re = /^.[^aeiyou]*/i\n\n full_name = name.capitalize # X\n suffixed = case full_name[0] # Y\n when 'A','E','I','O','U'\n name.downcase\n else\n full_name.sub(first_letter_and_consonants_re, '')\n end\n\n b_name = \"b#{suffixed}\"\n f_name = \"f#{suffixed}\"\n m_name = \"m#{suffixed}\"\n\n case full_name[0]\n when 'B'\n b_name = suffixed\n when 'F'\n f_name = suffixed\n when 'M'\n m_name = suffixed\n end\n\n puts <<~END_VERSE\n #{full_name}, #{full_name}, bo-#{b_name}\n Banana-fana fo-#{f_name}\n Fee-fi-mo-#{m_name}\n #{full_name}!\n\n END_VERSE\nend\n\n%w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name|\n print_verse name\nend\n\n"} {"title": "The Twelve Days of Christmas", "language": "Ruby", "task": "Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found here. \n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n", "solution": "gifts = \"A partridge in a pear tree\nTwo turtle doves and\nThree french hens\nFour calling birds\nFive golden rings\nSix geese a-laying\nSeven swans a-swimming\nEight maids a-milking\nNine ladies dancing\nTen lords a-leaping\nEleven pipers piping\nTwelve drummers drumming\".split(\"\\n\")\n\ndays = %w(first second third fourth fifth sixth\nseventh eighth ninth tenth eleventh twelfth)\n\ndays.each_with_index do |day, i| \n puts \"On the #{day} day of Christmas\"\n puts \"My true love gave to me:\"\n puts gifts[0, i+1].reverse\n puts\nend"} {"title": "Top rank per group", "language": "Ruby 2.2+", "task": "Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "solution": "require \"csv\"\n\ndata = <true, :header_converters=>:symbol)\n groups = table.group_by{|emp| emp[:department]}.sort\n groups.each do |dept, emps|\n puts dept\n # max by salary\n emps.max_by(n) {|emp| emp[:salary].to_i}.each do |e|\n puts \" %-16s %6s %7d\" % [e[:employee_name], e[:employee_id], e[:salary]]\n end\n puts\n end\nend\n\nshow_top_salaries_per_group(data, 3)"} {"title": "Topic variable", "language": "Ruby", "task": "Several programming languages offer syntax shortcuts to deal with the notion of \"current\" or \"topic\" variable.\n\nA topic variable is a special variable with a very short name which can also often be omitted.\n\nDemonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.\n\nFor instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 to it and then computing its square and square root.\n\n", "solution": "while DATA.gets # assigns to $_ (local scope)\n print # If no arguments are given, prints $_\nend\n__END__\nThis is line one\nThis is line two\nThis is line three"} {"title": "Topswops", "language": "Ruby from Python", "task": "Topswops is a card game created by John Conway in the 1970's.\n\n\nAssume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. \n\nA round is composed of reversing the first m cards where m is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. \n\n\nFor our example the swaps produce:\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n\nFor a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.\n\n\nFor a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.\n\n\n;Task:\nThe task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.\n\n\n;Note:\nTopswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.\n\n\n;Related tasks:\n* [[Number reversal game]]\n* [[Sorting algorithms/Pancake sort]]\n\n", "solution": "def f1(a)\n i = 0\n while (a0 = a[0]) > 1\n a[0...a0] = a[0...a0].reverse\n i += 1\n end\n i\nend\n\ndef fannkuch(n)\n [*1..n].permutation.map{|a| f1(a)}.max\nend\n\nfor n in 1..10\n puts \"%2d : %d\" % [n, fannkuch(n)]\nend"} {"title": "Topswops", "language": "Ruby from Java", "task": "Topswops is a card game created by John Conway in the 1970's.\n\n\nAssume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. \n\nA round is composed of reversing the first m cards where m is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. \n\n\nFor our example the swaps produce:\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n\nFor a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.\n\n\nFor a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.\n\n\n;Task:\nThe task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.\n\n\n;Note:\nTopswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.\n\n\n;Related tasks:\n* [[Number reversal game]]\n* [[Sorting algorithms/Pancake sort]]\n\n", "solution": "def try_swaps(deck, f, d, n)\n @best[n] = d if d > @best[n]\n (n-1).downto(0) do |i|\n break if deck[i] == -1 || deck[i] == i\n return if d + @best[i] <= @best[n]\n end\n deck2 = deck.dup\n for i in 1...n\n k = 1 << i\n if deck2[i] == -1\n next if f & k != 0\n elsif deck2[i] != i\n next\n end\n deck2[0] = i\n deck2[1..i] = deck[0...i].reverse\n try_swaps(deck2, f | k, d+1, n)\n end\nend\n\ndef topswops(n)\n @best[n] = 0\n deck0 = [-1] * (n + 1)\n try_swaps(deck0, 1, 0, n)\n @best[n]\nend\n\n@best = [0] * 16\nfor i in 1..10\n puts \"%2d : %d\" % [i, topswops(i)]\nend"} {"title": "Total circles area", "language": "Ruby", "task": "Example circles\nExample circles filtered\n\nGiven some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. \n\nOne point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.\n\nTo allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):\n\n xc yc radius\n 1.6417233788 1.6121789534 0.0848270516\n -1.4944608174 1.2077959613 1.1039549836\n 0.6110294452 -0.6907087527 0.9089162485\n 0.3844862411 0.2923344616 0.2375743054\n -0.2495892950 -0.3832854473 1.0845181219\n 1.7813504266 1.6178237031 0.8162655711\n -0.1985249206 -0.8343333301 0.0538864941\n -1.7011985145 -0.1263820964 0.4776976918\n -0.4319462812 1.4104420482 0.7886291537\n 0.2178372997 -0.9499557344 0.0357871187\n -0.6294854565 -1.3078893852 0.7653357688\n 1.7952608455 0.6281269104 0.2727652452\n 1.4168575317 1.0683357171 1.1016025378\n 1.4637371396 0.9463877418 1.1846214562\n -0.5263668798 1.7315156631 1.4428514068\n -1.2197352481 0.9144146579 1.0727263474\n -0.1389358881 0.1092805780 0.7350208828\n 1.5293954595 0.0030278255 1.2472867347\n -0.5258728625 1.3782633069 1.3495508831\n -0.1403562064 0.2437382535 1.3804956588\n 0.8055826339 -0.0482092025 0.3327165165\n -0.6311979224 0.7184578971 0.2491045282\n 1.4685857879 -0.8347049536 1.3670667538\n -0.6855727502 1.6465021616 1.0593087096\n 0.0152957411 0.0638919221 0.9771215985\n\n\nThe result is 21.56503660... .\n\n\n;Related task:\n* [[Circles of given radius through two points]].\n\n\n;See also:\n* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/\n* http://stackoverflow.com/a/1667789/10562\n\n", "solution": "circles = [\n [ 1.6417233788, 1.6121789534, 0.0848270516],\n [-1.4944608174, 1.2077959613, 1.1039549836],\n [ 0.6110294452, -0.6907087527, 0.9089162485],\n [ 0.3844862411, 0.2923344616, 0.2375743054],\n [-0.2495892950, -0.3832854473, 1.0845181219],\n [ 1.7813504266, 1.6178237031, 0.8162655711],\n [-0.1985249206, -0.8343333301, 0.0538864941],\n [-1.7011985145, -0.1263820964, 0.4776976918],\n [-0.4319462812, 1.4104420482, 0.7886291537],\n [ 0.2178372997, -0.9499557344, 0.0357871187],\n [-0.6294854565, -1.3078893852, 0.7653357688],\n [ 1.7952608455, 0.6281269104, 0.2727652452],\n [ 1.4168575317, 1.0683357171, 1.1016025378],\n [ 1.4637371396, 0.9463877418, 1.1846214562],\n [-0.5263668798, 1.7315156631, 1.4428514068],\n [-1.2197352481, 0.9144146579, 1.0727263474],\n [-0.1389358881, 0.1092805780, 0.7350208828],\n [ 1.5293954595, 0.0030278255, 1.2472867347],\n [-0.5258728625, 1.3782633069, 1.3495508831],\n [-0.1403562064, 0.2437382535, 1.3804956588],\n [ 0.8055826339, -0.0482092025, 0.3327165165],\n [-0.6311979224, 0.7184578971, 0.2491045282],\n [ 1.4685857879, -0.8347049536, 1.3670667538],\n [-0.6855727502, 1.6465021616, 1.0593087096],\n [ 0.0152957411, 0.0638919221, 0.9771215985],\n]\n\ndef minmax_circle(circles)\n xmin = circles.map {|xc, yc, radius| xc - radius}.min\n xmax = circles.map {|xc, yc, radius| xc + radius}.max\n ymin = circles.map {|xc, yc, radius| yc - radius}.min\n ymax = circles.map {|xc, yc, radius| yc + radius}.max\n [xmin, xmax, ymin, ymax]\nend\n\n# remove internal circle\ndef select_circle(circles)\n circles = circles.sort_by{|cx,cy,r| -r}\n size = circles.size\n select = [*0...size]\n for i in 0...size-1\n xi,yi,ri = circles[i].to_a\n for j in i+1...size\n xj,yj,rj = circles[j].to_a\n select -= [j] if (xi-xj)**2 + (yi-yj)**2 <= (ri-rj)**2\n end\n end\n circles.values_at(*select)\nend\ncircles = select_circle(circles)"} {"title": "Total circles area", "language": "Ruby from Python", "task": "Example circles\nExample circles filtered\n\nGiven some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. \n\nOne point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.\n\nTo allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):\n\n xc yc radius\n 1.6417233788 1.6121789534 0.0848270516\n -1.4944608174 1.2077959613 1.1039549836\n 0.6110294452 -0.6907087527 0.9089162485\n 0.3844862411 0.2923344616 0.2375743054\n -0.2495892950 -0.3832854473 1.0845181219\n 1.7813504266 1.6178237031 0.8162655711\n -0.1985249206 -0.8343333301 0.0538864941\n -1.7011985145 -0.1263820964 0.4776976918\n -0.4319462812 1.4104420482 0.7886291537\n 0.2178372997 -0.9499557344 0.0357871187\n -0.6294854565 -1.3078893852 0.7653357688\n 1.7952608455 0.6281269104 0.2727652452\n 1.4168575317 1.0683357171 1.1016025378\n 1.4637371396 0.9463877418 1.1846214562\n -0.5263668798 1.7315156631 1.4428514068\n -1.2197352481 0.9144146579 1.0727263474\n -0.1389358881 0.1092805780 0.7350208828\n 1.5293954595 0.0030278255 1.2472867347\n -0.5258728625 1.3782633069 1.3495508831\n -0.1403562064 0.2437382535 1.3804956588\n 0.8055826339 -0.0482092025 0.3327165165\n -0.6311979224 0.7184578971 0.2491045282\n 1.4685857879 -0.8347049536 1.3670667538\n -0.6855727502 1.6465021616 1.0593087096\n 0.0152957411 0.0638919221 0.9771215985\n\n\nThe result is 21.56503660... .\n\n\n;Related task:\n* [[Circles of given radius through two points]].\n\n\n;See also:\n* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/\n* http://stackoverflow.com/a/1667789/10562\n\n", "solution": "def area_scan(prec, circles)\n sect = ->(y) do\n circles.select{|cx,cy,r| (y - cy).abs < r}.map do |cx,cy,r|\n dr = Math.sqrt(r ** 2 - (y - cy) ** 2)\n [cx - dr, cx + dr]\n end\n end\n xmin, xmax, ymin, ymax = minmax_circle(circles)\n ymin = (ymin / prec).floor\n ymax = (ymax / prec).ceil\n \n total = 0\n for y in ymin..ymax\n y *= prec\n right = xmin\n for x0, x1 in sect[y].sort\n next if x1 <= right\n total += x1 - [x0, right].max\n right = x1\n end\n end\n total * prec\nend\n\nputs \"Scanline Method\"\nprec = 1e-2\n3.times do\n t0 = Time.now\n puts \"%8.6f : %12.9f, %p sec\" % [prec, area_scan(prec, circles), Time.now-t0]\n prec /= 10\nend"} {"title": "Trabb Pardo\u2013Knuth algorithm", "language": "Ruby", "task": "The TPK algorithm is an early example of a programming chrestomathy. \nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. \nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n '''ask''' for 11 numbers to be read into a sequence ''S''\n '''reverse''' sequence ''S''\n '''for each''' ''item'' '''in''' sequence ''S''\n ''result'' ''':=''' '''call''' a function to do an ''operation''\n '''if''' ''result'' overflows\n '''alert''' user\n '''else'''\n '''print''' ''result''\n\nThe task is to implement the algorithm:\n# Use the function: f(x) = |x|^{0.5} + 5x^3\n# The overflow condition is an answer of greater than 400.\n# The 'user alert' should not stop processing of other items of the sequence.\n# Print a prompt before accepting '''eleven''', textual, numeric inputs.\n# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.\n# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).\n\n", "solution": "def f(x) x.abs ** 0.5 + 5 * x ** 3 end\n\nputs \"Please enter 11 numbers:\"\nnums = 11.times.map{ gets.to_f }\n\nnums.reverse_each do |n|\n print \"f(#{n}) = \"\n res = f(n)\n puts res > 400 ? \"Overflow!\" : res\nend"} {"title": "Truncate a file", "language": "Ruby", "task": "Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).\n\n\nTruncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be \"binary safe\", leaving the contents of the untruncated part of the file unchanged.\n\nIf the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. \n\nOn some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. \n\nThis task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.\n\n", "solution": "# Open a file for writing, and truncate it to 1234 bytes.\nFile.open(\"file\", \"ab\") do |f|\n f.truncate(1234)\n f << \"Killroy was here\" # write to file\nend # file is closed now.\n\n# Just truncate a file to 567 bytes.\nFile.truncate(\"file\", 567)"} {"title": "Truth table", "language": "Ruby", "task": "A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.\n\n\n;Task:\n# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).\n# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. \n# Either reverse-polish or infix notation expressions are allowed.\n\n\n;Related tasks:\n* [[Boolean values]]\n* [[Ternary logic]]\n\n\n;See also:\n* Wolfram MathWorld entry on truth tables.\n* some \"truth table\" examples from Google.\n\n", "solution": "loop do\n print \"\\ninput a boolean expression (e.g. 'a & b'): \"\n expr = gets.strip.downcase \n break if expr.empty?\n\n vars = expr.scan(/\\p{Alpha}+/)\n if vars.empty?\n puts \"no variables detected in your boolean expression\"\n next\n end\n\n vars.each {|v| print \"#{v}\\t\"}\n puts \"| #{expr}\"\n\n prefix = []\n suffix = []\n vars.each do |v|\n prefix << \"[false, true].each do |#{v}|\"\n suffix << \"end\"\n end\n\n body = vars.inject(\"puts \") {|str, v| str + \"#{v}.to_s + '\\t' + \"} \n body += '\"| \" + eval(expr).to_s'\n\n eval (prefix + [body] + suffix).join(\"\\n\")\nend"} {"title": "Two bullet roulette", "language": "Ruby", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "class Revolver\n attr_accessor :strategy\n attr_reader :notches, :shot_count\n\n def initialize(strategy = [:load, :spin, :shoot], num_chambers = 6) # default like Deer hunter\n @chambers = Array.new(num_chambers) # by default 6 nils\n @strategy = strategy\n @notches, @shot_count, @loaded_count = 0, 0, 0\n end\n\n def load\n raise \"gun completely loaded \" if @chambers.all? :loaded\n @chambers.rotate! until @chambers[1] == nil #not sure about this; Raku rotates -1\n @chambers[1] = :loaded\n @chambers.rotate! #not sure about this; Raku rotates -1\n @loaded_count += 1\n end\n\n def spin\n @chambers.rotate!(rand(1..@chambers.size))\n end\n\n def unload\n @chambers.fill(nil)\n @loaded_count = 0\n end\n\n def shoot\n @chambers[0] = nil\n @chambers.rotate!\n end\n\n def play\n strategy.each{|action| send(action)}\n @shot_count += 1\n @notches += 1 unless @chambers.count(:loaded) == @loaded_count # all bullets still there?\n unload\n end\nend\n\nstrategies = {:A => [:load, :spin, :load, :spin, :shoot, :spin, :shoot],\n :B => [:load, :spin, :load, :spin, :shoot, :shoot],\n :C => [:load, :load, :spin, :shoot, :spin, :shoot],\n :D => [:load, :load, :spin, :shoot, :shoot],\n :E => [:load, :spin, :shoot, :load, :spin, :shoot]}\n\nn = 100_000\nputs \"simulation of #{n} runs:\"\nstrategies.each do |name, strategy|\n gun = Revolver.new(strategy) # Revolver.new(strategy, 10) for a 10-shooter\n n.times{gun.play}\n puts \"Strategy #{name}: #{gun.notches.fdiv(gun.shot_count)}\"\nend\n"} {"title": "UPC", "language": "Ruby from C", "task": "Goal: \nConvert UPC bar codes to decimal.\n\n\nSpecifically:\n\nThe UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... \n\nHere, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink).\n\n\n;Sample input:\nBelow, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:\n\n # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \n # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \n # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \n # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \n # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \n # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \n # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \n # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \n # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \n # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \n\nSome of these were entered upside down, and one entry has a timing error.\n\n\n;Task:\nImplement code to find the corresponding decimal representation of each, rejecting the error. \n\nExtra credit for handling the rows entered upside down (the other option is to reject them).\n\n\n;Notes:\nEach digit is represented by 7 bits:\n\n 0: 0 0 0 1 1 0 1\n 1: 0 0 1 1 0 0 1\n 2: 0 0 1 0 0 1 1\n 3: 0 1 1 1 1 0 1\n 4: 0 1 0 0 0 1 1\n 5: 0 1 1 0 0 0 1\n 6: 0 1 0 1 1 1 1\n 7: 0 1 1 1 0 1 1\n 8: 0 1 1 0 1 1 1\n 9: 0 0 0 1 0 1 1\n\nOn the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''. \nOn the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1''' \nAlternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code.\n\n\n\n;The UPC-A bar code structure:\n::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly), \n::* then has a ''' # # ''' sequence marking the start of the sequence, \n::* then has the six \"left hand\" digits, \n::* then has a ''' # # ''' sequence in the middle, \n::* then has the six \"right hand digits\", \n::* then has another ''' # # ''' (end sequence), and finally, \n::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).\n\n\nFinally, the last digit is a checksum digit which may be used to help detect errors. \n\n\n;Verification:\nMultiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.\n\nThe sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.\n\n", "solution": "DIGIT_F = {\n \" ## #\" => 0,\n \" ## #\" => 1,\n \" # ##\" => 2,\n \" #### #\" => 3,\n \" # ##\" => 4,\n \" ## #\" => 5,\n \" # ####\" => 6,\n \" ### ##\" => 7,\n \" ## ###\" => 8,\n \" # ##\" => 9,\n}\n\nDIGIT_R = {\n \"### # \" => 0,\n \"## ## \" => 1,\n \"## ## \" => 2,\n \"# # \" => 3,\n \"# ### \" => 4,\n \"# ### \" => 5,\n \"# # \" => 6,\n \"# # \" => 7,\n \"# # \" => 8,\n \"### # \" => 9,\n}\n\nEND_SENTINEL = \"# #\"\nMID_SENTINEL = \" # # \"\n\ndef decode_upc(s)\n def decode_upc_impl(input)\n upc = input.strip\n if upc.length != 95 then\n return false\n end\n\n pos = 0\n digits = []\n sum = 0\n\n # end sentinel\n if upc[pos .. pos + 2] == END_SENTINEL then\n pos += 3\n else\n return false\n end\n\n # 6 left hand digits\n for i in 0 .. 5\n digit = DIGIT_F[upc[pos .. pos + 6]]\n if digit == nil then\n return false\n else\n digits.push(digit)\n sum += digit * [1, 3][digits.length % 2]\n pos += 7\n end\n end\n\n # mid sentinel\n if upc[pos .. pos + 4] == MID_SENTINEL then\n pos += 5\n else\n return false\n end\n\n # 6 right hand digits\n for i in 0 .. 5\n digit = DIGIT_R[upc[pos .. pos + 6]]\n if digit == nil then\n return false\n else\n digits.push(digit)\n sum += digit * [1, 3][digits.length % 2]\n pos += 7\n end\n end\n\n # end sentinel\n if upc[pos .. pos + 2] == END_SENTINEL then\n pos += 3\n else\n return false\n end\n\n if sum % 10 == 0 then\n print digits, \" \"\n return true\n else\n print \"Failed Checksum \"\n return false\n end\n end\n\n if decode_upc_impl(s) then\n puts \"Rightside Up\"\n elsif decode_upc_impl(s.reverse) then\n puts \"Upside Down\"\n else\n puts \"Invalid digit(s)\"\n end\nend\n\ndef main\n num = 0\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \")\n\n print \"%2d: \" % [num += 1]\n decode_upc(\" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \")\nend\n\nmain()"} {"title": "URL decoding", "language": "Ruby", "task": "This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* The encoded string \"http%3A%2F%2Ffoo%20bar%2F\" should be reverted to the unencoded form \"http://foo bar/\".\n\n* The encoded string \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" should revert to the unencoded form \"google.com/search?q=`Abdu'l-Baha\".\n\n* The encoded string \"%25%32%35\" should revert to the unencoded form \"%25\" and '''not''' \"%\".\n\n", "solution": "require 'cgi'\nputs CGI.unescape(\"http%3A%2F%2Ffoo%20bar%2F\")\n# => \"http://foo bar/\""} {"title": "URL decoding", "language": "Ruby 1.9.2", "task": "This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* The encoded string \"http%3A%2F%2Ffoo%20bar%2F\" should be reverted to the unencoded form \"http://foo bar/\".\n\n* The encoded string \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" should revert to the unencoded form \"google.com/search?q=`Abdu'l-Baha\".\n\n* The encoded string \"%25%32%35\" should revert to the unencoded form \"%25\" and '''not''' \"%\".\n\n", "solution": "require 'uri'\nputs URI.decode_www_form_component(\"http%3A%2F%2Ffoo%20bar%2F\")\n# => \"http://foo bar/\""} {"title": "URL encoding", "language": "Ruby", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "require 'cgi'\nputs CGI.escape(\"http://foo bar/\").gsub(\"+\", \"%20\")\n# => \"http%3A%2F%2Ffoo%20bar%2F\""} {"title": "URL encoding", "language": "Ruby 1.9.2", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "require 'uri'\nputs URI.encode_www_form_component(\"http://foo bar/\").gsub(\"+\", \"%20\")\n# => \"http%3A%2F%2Ffoo%20bar%2F\""} {"title": "URL parser", "language": "Ruby", "task": "URLs are strings with a simple syntax:\n scheme://[username:password@]domain[:port]/path?query_string#fragment_id\n\n\n;Task:\nParse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ...\n\n\nNote: this task has nothing to do with [[URL encoding]] or [[URL decoding]].\n\n\nAccording to the standards, the characters:\n:::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ] \nonly need to be percent-encoded ('''%''') in case of possible confusion. \n\nAlso note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.\n\nThe way the returned information is provided (set of variables, array, structured, record, object,...) \nis language-dependent and left to the programmer, but the code should be clear enough to reuse.\n\nExtra credit is given for clear error diagnostics.\n\n* Here is the official standard: https://tools.ietf.org/html/rfc3986, \n* and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.\n\n\n;Test cases:\nAccording to T. Berners-Lee\n \n'''foo://example.com:8042/over/there?name=ferret#nose''' should parse into:\n::* scheme = foo\n::* domain = example.com\n::* port = :8042\n::* path = over/there\n::* query = name=ferret\n::* fragment = nose\n\n\n'''urn:example:animal:ferret:nose''' should parse into:\n::* scheme = urn\n::* path = example:animal:ferret:nose\n\n\n'''other URLs that must be parsed include:'''\n:* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true \n:* ftp://ftp.is.co.za/rfc/rfc1808.txt \n:* http://www.ietf.org/rfc/rfc2396.txt#header1 \n:* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two \n:* mailto:John.Doe@example.com \n:* news:comp.infosystems.www.servers.unix \n:* tel:+1-816-555-1212 \n:* telnet://192.0.2.16:80/ \n:* urn:oasis:names:specification:docbook:dtd:xml:4.1.2 \n\n", "solution": "require 'uri'\n\ntest_cases = [\n \"foo://example.com:8042/over/there?name=ferret#nose\",\n \"urn:example:animal:ferret:nose\",\n \"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\",\n \"ftp://ftp.is.co.za/rfc/rfc1808.txt\",\n \"http://www.ietf.org/rfc/rfc2396.txt#header1\",\n \"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\",\n \"mailto:John.Doe@example.com\",\n \"news:comp.infosystems.www.servers.unix\",\n \"tel:+1-816-555-1212\",\n \"telnet://192.0.2.16:80/\",\n \"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n \"ssh://alice@example.com\",\n \"https://bob:pass@example.com/place\",\n \"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64\"\n]\n\nclass URI::Generic; alias_method :domain, :host; end\n\ntest_cases.each do |test_case|\n puts test_case\n uri = URI.parse(test_case)\n %w[ scheme domain port path query fragment user password ].each do |attr|\n puts \" #{attr.rjust(8)} = #{uri.send(attr)}\" if uri.send(attr)\n end\nend"} {"title": "UTF-8 encode and decode", "language": "Ruby", "task": "As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.\n\nThe goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.\n\nDemonstrate the functionality of your encoder and decoder on the following five characters:\n\n\nCharacter Name Unicode UTF-8 encoding (hex)\n---------------------------------------------------------------------------------\nA LATIN CAPITAL LETTER A U+0041 41\no LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\nZh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\nEUR EURO SIGN U+20AC E2 82 AC\n MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "character_arr = [\"A\",\"\u00f6\",\"\u0416\",\"\u20ac\",\"\ud834\udd1e\"]\nfor c in character_arr do\n puts \"Character: \" + c.encode(\"utf-8\")\n puts \"Code-Point: #{c.encode(\"utf-8\").ord.to_s(16).upcase}\"\n puts \"Code-Units: \" + c.each_byte.map { |n| '%02X ' % (n & 0xFF) }.join\n puts \"\"\nend\n"} {"title": "Ultra useful primes", "language": "Ruby", "task": "An '''ultra-useful prime''' is a member of the sequence where each '''a(n)''' is the smallest positive integer '''k''' such that '''2(2n) - k''' is prime.\n\n'''''k''' must always be an odd number since 2 to any power is always even.''\n\n\n;Task\n\n* Find and show here, on this page, the first '''10''' elements of the sequence.\n\n\n;Stretch \n\n* Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)\n\n\n;See also\n\n* OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime\n \n\n", "solution": "require 'openssl'\n\n(1..10).each do |n|\n pow = 2 ** (2 ** n)\n print \"#{n}:\\t\"\n puts (1..).step(2).detect{|k| OpenSSL::BN.new(pow-k).prime?}\nend"} {"title": "Unbias a random generator", "language": "Ruby", "task": "Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.\n\n;Task details:\n* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.\n* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.\n* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).\n\n\nThe actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.\n\nThis task is an implementation of Von Neumann debiasing, first described in a 1951 paper.\n\n", "solution": "def rand_n(bias)\n rand(bias) == 0 ? 1 : 0\nend\n\ndef unbiased(bias)\n a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0\n a\nend\n\nruns = 1_000_000\nkeys = %i(bias biased unbiased) #use [:bias,:biased,:unbiased] in Ruby < 2.0\nputs keys.join(\"\\t\")\n\n(3..6).each do |bias|\n counter = Hash.new(0) # counter will respond with 0 when key is not known\n runs.times do\n counter[:biased] += 1 if rand_n(bias) == 1 #the first time, counter has no key for :biased, so it will respond 0\n counter[:unbiased] += 1 if unbiased(bias) == 1\n end\n counter[:bias] = bias\n puts counter.values_at(*keys).join(\"\\t\")\nend"} {"title": "Unicode strings", "language": "Ruby", "task": "As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend. \n\nIt is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. \n\nHow well prepared is your programming language for Unicode? \n\n\n;Task:\nDiscuss and demonstrate its unicode awareness and capabilities. \n\n\nSome suggested topics:\n:* How easy is it to present Unicode strings in source code? \n:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n:* How well can the language communicate with the rest of the world? \n:* Is it good at input/output with Unicode?\n:* Is it convenient to manipulate Unicode strings in the language?\n:* How broad/deep does the language support Unicode? \n:* What encodings (e.g. UTF-8, UTF-16, etc) can be used? \n:* Does it support normalization?\n\n\n;Note:\nThis task is a bit unusual in that it encourages general discussion rather than clever coding.\n\n\n;See also:\n* [[Unicode variable names]]\n* [[Terminal control/Display an extended character]]\n\n", "solution": "p bad = \"\u00bfcomo\\u0301 esta\\u0301s?\" # => \"\u00bfcom\u00f3 est\u00e1s?\"\np bad.unicode_normalized? # => false\np bad.unicode_normalize! # => \"\u00bfcom\u00f3 est\u00e1s?\"\np bad.unicode_normalized? # => true\n"} {"title": "Universal Turing machine", "language": "Ruby", "task": "One of the foundational mathematical constructs behind computer science \nis the universal Turing Machine. \n\n\n(Alan Turing introduced the idea of such a machine in 1936-1937.)\n\nIndeed one way to definitively prove that a language \nis turing-complete \nis to implement a universal Turing machine in it.\n\n\n;Task:\nSimulate such a machine capable \nof taking the definition of any other Turing machine and executing it. \n \nOf course, you will not have an infinite tape, \nbut you should emulate this as much as is possible. \n\nThe three permissible actions on the tape are \"left\", \"right\" and \"stay\".\n\nTo test your universal Turing machine (and prove your programming language \nis Turing complete!), you should execute the following two Turing machines \nbased on the following definitions.\n\n\n'''Simple incrementer'''\n* '''States:''' q0, qf\n* '''Initial state:''' q0\n* '''Terminating states:''' qf\n* '''Permissible symbols:''' B, 1\n* '''Blank symbol:''' B\n* '''Rules:'''\n** (q0, 1, 1, right, q0)\n** (q0, B, 1, stay, qf)\n\n\nThe input for this machine should be a tape of 1 1 1\n\n\n'''Three-state busy beaver'''\n* '''States:''' a, b, c, halt\n* '''Initial state:''' a\n* '''Terminating states:''' halt\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (a, 0, 1, right, b)\n** (a, 1, 1, left, c)\n** (b, 0, 1, left, a)\n** (b, 1, 1, right, b)\n** (c, 0, 1, left, b)\n** (c, 1, 1, stay, halt)\n\n\nThe input for this machine should be an empty tape.\n\n\n'''Bonus:'''\n\n'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''\n* '''States:''' A, B, C, D, E, H\n* '''Initial state:''' A\n* '''Terminating states:''' H\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (A, 0, 1, right, B)\n** (A, 1, 1, left, C)\n** (B, 0, 1, right, C)\n** (B, 1, 1, right, B)\n** (C, 0, 1, right, D)\n** (C, 1, 0, left, E)\n** (D, 0, 1, left, A)\n** (D, 1, 1, left, D)\n** (E, 0, 1, stay, H)\n** (E, 1, 0, left, A)\n\n\nThe input for this machine should be an empty tape.\n\nThis machine runs for more than 47 millions steps.\n\n", "solution": "class Turing\n class Tape\n def initialize(symbols, blank, starting_tape)\n @symbols = symbols\n @blank = blank\n @tape = starting_tape\n @index = 0\n end\n def read\n retval = @tape[@index]\n unless retval\n retval = @tape[@index] = @blank\n end\n raise \"invalid symbol '#{retval}' on tape\" unless @tape.member?(retval)\n return retval\n end\n def write(symbol)\n @tape[@index] = symbol\n end\n def right\n @index += 1\n end\n def left\n if @index == 0\n @tape.unshift @blank\n else\n @index -= 1\n end\n end\n def stay\n # nop\n end\n def get_tape\n return @tape\n end\n end\n\n def initialize(symbols, blank,\n initial_state, halt_states, running_states,\n rules, starting_tape = [])\n @tape = Tape.new(symbols, blank, starting_tape)\n @initial_state = initial_state\n @halt_states = halt_states\n @running_states = running_states\n @rules = rules\n @halted = false\n end\n def run\n raise \"machine already halted\" if @halted\n state = @initial_state\n while (true)\n break if @halt_states.member? state\n raise \"unknown state '#{state}'\" unless @running_states.member? state\n symbol = @tape.read\n outsym, action, state = @rules[state][symbol]\n @tape.write outsym\n @tape.send action\n end\n @halted = true\n return @tape.get_tape\n end\nend"} {"title": "Validate International Securities Identification Number", "language": "Ruby", "task": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. \n\n\n;Task:\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, ''and'' the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n;Details:\nThe format of an ISIN is as follows:\n\n\n\n+------------- a 2-character ISO country code (A-Z)\n| +----------- a 9-character security code (A-Z, 0-9)\n| | +-- a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.\n# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)\n\n\n;Test cases:\n:::: {| class=\"wikitable\"\n! ISIN\n! Validity\n! Comment\n|-\n| US0378331005 || valid || \n|-\n| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.\n|-\n| U50378331005 || not valid || The substitution typo is caught by the format constraint.\n|-\n| US03378331005 || not valid || The duplication typo is caught by the format constraint.\n|-\n| AU0000XVGZA3 || valid || \n|-\n| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.\n|-\n| FR0000988040 || valid || \n|}\n\n(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* Interactive online ISIN validator\n* Wikipedia article: International Securities Identification Number\n\n", "solution": "RE = /\\A[A-Z]{2}[A-Z0-9]{9}[0-9]{1}\\z/\n\ndef valid_isin?(str)\n return false unless str =~ RE\n luhn(str.chars.map{|c| c.to_i(36)}.join)\nend\n\np %w(US0378331005\nUS0373831005\nU50378331005\nUS03378331005\nAU0000XVGZA3\nAU0000VXGZA3\nFR0000988040).map{|tc| valid_isin?(tc) }\t \n \n# => [true, false, false, false, true, true, true]"} {"title": "Van Eck sequence", "language": "Ruby", "task": "The sequence is generated by following this pseudo-code:\n\nA: The first term is zero.\n Repeatedly apply:\n If the last term is *new* to the sequence so far then:\nB: The next term is zero.\n Otherwise:\nC: The next term is how far back this last term occured previously.\n\n\n\n;Example:\nUsing A:\n:0\nUsing B:\n:0 0\nUsing C:\n:0 0 1\nUsing B:\n:0 0 1 0\nUsing C: (zero last occurred two steps back - before the one)\n:0 0 1 0 2\nUsing B:\n:0 0 1 0 2 0\nUsing C: (two last occurred two steps back - before the zero)\n:0 0 1 0 2 0 2 2\nUsing C: (two last occurred one step back)\n:0 0 1 0 2 0 2 2 1\nUsing C: (one last appeared six steps back)\n:0 0 1 0 2 0 2 2 1 6\n...\n\n\n;Task:\n# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.\n# Use it to display here, on this page:\n:# The first ten terms of the sequence.\n:# Terms 991 - to - 1000 of the sequence.\n\n\n;References:\n* Don't Know (the Van Eck Sequence) - Numberphile video.\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "van_eck = Enumerator.new do |y|\n ar = [0]\n loop do\n y << (term = ar.last) # yield\n ar << (ar.count(term)==1 ? 0 : ar.size - 1 - ar[0..-2].rindex(term))\n end\nend\n\nve = van_eck.take(1000)\np ve.first(10), ve.last(10)\n"} {"title": "Van der Corput sequence", "language": "Ruby", "task": "When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.\n\nSo in the following table:\n 0.\n 1.\n 10.\n 11.\n ...\nthe binary number \"10\" is 1 \\times 2^1 + 0 \\times 2^0.\n\nYou can also have binary digits to the right of the \"point\", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. \nThe weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.\n\nIf you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.\n\n .0\n .1\n .01\n .11\n ...\n\nThe third member of the sequence, binary 0.01, is therefore 0 \\times 2^{-1} + 1 \\times 2^{-2} or 1/4.\n\n Monte Carlo simulations. \nThis sequence is also a superset of the numbers representable by the \"fraction\" field of an old IEEE floating point standard. In that standard, the \"fraction\" field represented the fractional part of a binary number beginning with \"1.\" e.g. 1.101001101.\n\n'''Hint'''\n\nA ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:\n>>> def base10change(n, base):\n\tdigits = []\n\twhile n:\n\t\tn,remainder = divmod(n, base)\n\t\tdigits.insert(0, remainder)\n\treturn digits\n\n>>> base10change(11, 2)\n[1, 0, 1, 1]\nthe above showing that 11 in decimal is 1\\times 2^3 + 0\\times 2^2 + 1\\times 2^1 + 1\\times 2^0.\nReflected this would become .1101 or 1\\times 2^{-1} + 1\\times 2^{-2} + 0\\times 2^{-3} + 1\\times 2^{-4}\n\n\n;Task description:\n* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.\n* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).\n\n* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.\n\n\n\n;See also:\n* The Basic Low Discrepancy Sequences\n* [[Non-decimal radices/Convert]]\n* Van der Corput sequence\n\n", "solution": "def vdc(n, base=2)\n str = n.to_s(base).reverse\n str.to_i(base).quo(base ** str.length)\nend\n\n(2..5).each do |base|\n puts \"Base #{base}: \" + Array.new(10){|i| vdc(i,base)}.join(\", \")\nend"} {"title": "Vector products", "language": "Ruby", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). \n\nIf you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.\n\nGiven the vectors:\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \nthen the following common vector products are defined:\n* '''The dot product''' (a scalar quantity)\n:::: A * B = a1b1 + a2b2 + a3b3 \n* '''The cross product''' (a vector quantity)\n:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) \n* '''The scalar triple product''' (a scalar quantity)\n:::: A * (B x C) \n* '''The vector triple product''' (a vector quantity)\n:::: A x (B x C) \n\n\n;Task:\nGiven the three vectors: \n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n# Create a named function/subroutine/method to compute the dot product of two vectors.\n# Create a function to compute the cross product of two vectors.\n# Optionally create a function to compute the scalar triple product of three vectors.\n# Optionally create a function to compute the vector triple product of three vectors.\n# Compute and display: a * b\n# Compute and display: a x b\n# Compute and display: a * (b x c), the scalar triple product.\n# Compute and display: a x (b x c), the vector triple product.\n\n\n;References:\n* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.\n* Wikipedia dot product. \n* Wikipedia cross product. \n* Wikipedia triple product.\n\n\n;Related tasks:\n* [[Dot product]]\n* [[Quaternion type]]\n\n", "solution": "require 'matrix'\n\nclass Vector\n def scalar_triple_product(b, c)\n self.inner_product(b.cross_product c)\n end\n\n def vector_triple_product(b, c)\n self.cross_product(b.cross_product c)\n end\nend\n\na = Vector[3, 4, 5]\nb = Vector[4, 3, 5]\nc = Vector[-5, -12, -13]\n\nputs \"a dot b = #{a.inner_product b}\"\nputs \"a cross b = #{a.cross_product b}\"\nputs \"a dot (b cross c) = #{a.scalar_triple_product b, c}\"\nputs \"a cross (b cross c) = #{a.vector_triple_product b, c}\""} {"title": "Visualize a tree", "language": "Ruby", "task": "A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n\n", "solution": "root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]\n"} {"title": "Vogel's approximation method", "language": "Ruby", "task": "Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them \"A\", \"B\", \"C\", \"D\", and \"E\". They estimate that:\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called \"W\", \"X\", \"Y\", and \"Z\".\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.\n\nRepeat until all supply and demand is met:\n\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\nFinally calculate the cost of your solution. In the example given it is PS3100:\n\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n\nThe optimal solution determined by GLPK is PS3100:\n\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n\n;Cf.\n* Transportation problem\n\n", "solution": "# VAM\n#\n# Nigel_Galloway\n# September 1st., 2013\nCOSTS = {W: {A: 16, B: 16, C: 13, D: 22, E: 17},\n X: {A: 14, B: 14, C: 13, D: 19, E: 15},\n Y: {A: 19, B: 19, C: 20, D: 23, E: 50},\n Z: {A: 50, B: 12, C: 50, D: 15, E: 11}}\ndemand = {A: 30, B: 20, C: 70, D: 30, E: 60}\nsupply = {W: 50, X: 60, Y: 50, Z: 50}\nCOLS = demand.keys\nres = {}; COSTS.each_key{|k| res[k] = Hash.new(0)}\ng = {}; supply.each_key{|x| g[x] = COSTS[x].keys.sort_by{|g| COSTS[x][g]}}\n demand.each_key{|x| g[x] = COSTS.keys.sort_by{|g| COSTS[g][x]}}\n\nuntil g.empty? \n d = demand.collect{|x,y| [x, z = COSTS[g[x][0]][x], g[x][1] ? COSTS[g[x][1]][x] - z : z]}\n dmax = d.max_by{|n| n[2]}\n d = d.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}\n s = supply.collect{|x,y| [x, z = COSTS[x][g[x][0]], g[x][1] ? COSTS[x][g[x][1]] - z : z]}\n dmax = s.max_by{|n| n[2]}\n s = s.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}\n t,f = d[2]==s[2] ? [s[1], d[1]] : [d[2],s[2]] \n d,s = t > f ? [d[0],g[d[0]][0]] : [g[s[0]][0],s[0]]\n v = [supply[s], demand[d]].min\n res[s][d] += v\n demand[d] -= v\n if demand[d] == 0 then\n supply.reject{|k, n| n == 0}.each_key{|x| g[x].delete(d)}\n g.delete(d)\n demand.delete(d)\n end\n supply[s] -= v\n if supply[s] == 0 then\n demand.reject{|k, n| n == 0}.each_key{|x| g[x].delete(s)}\n g.delete(s)\n supply.delete(s)\n end\nend\n\nCOLS.each{|n| print \"\\t\", n}\nputs\ncost = 0\nCOSTS.each_key do |g|\n print g, \"\\t\"\n COLS.each do |n|\n y = res[g][n]\n print y if y != 0\n cost += y * COSTS[g][n]\n print \"\\t\"\n end\n puts\nend\nprint \"\\n\\nTotal Cost = \", cost"} {"title": "Voronoi diagram", "language": "Ruby", "task": "A Voronoi diagram is a diagram consisting of a number of sites. \n\nEach Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.\n\n\n;Task:\nDemonstrate how to generate and display a Voroni diagram. \n\n\nSee algo [[K-means++ clustering]].\n\n", "solution": "# frozen_string_literal: true\n\nrequire_relative 'raster_graphics'\n\nclass ColourPixel < Pixel\n def initialize(x, y, colour)\n @colour = colour\n super x, y\n end\n attr_accessor :colour\n\n def distance_to(px, py)\n Math.hypot(px - x, py - y)\n end\nend\n\nwidth = 300\nheight = 200\nnpoints = 20\npixmap = Pixmap.new(width, height)\n\n@bases = npoints.times.collect do |_i|\n ColourPixel.new(\n 3 + rand(width - 6), 3 + rand(height - 6), # provide a margin to draw a circle\n RGBColour.new(rand(256), rand(256), rand(256))\n )\nend\n\npixmap.each_pixel do |x, y|\n nearest = @bases.min_by { |base| base.distance_to(x, y) }\n pixmap[x, y] = nearest.colour\nend\n\n@bases.each do |base|\n pixmap[base.x, base.y] = RGBColour::BLACK\n pixmap.draw_circle(base, 2, RGBColour::BLACK)\nend\n\npixmap.save_as_png('voronoi_rb.png')"} {"title": "Wagstaff primes", "language": "Ruby", "task": "Definition\nA ''Wagstaff prime'' is a prime number of the form ''(2^p + 1)/3'' where the exponent ''p'' is an odd prime.\n\n;Example \n(2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes.\n\n;Task\nFind and show here the first ''10'' Wagstaff primes and their corresponding exponents ''p''.\n\n;Stretch (requires arbitrary precision integers)\nFind and show here the exponents ''p'' corresponding to the next ''14'' Wagstaff primes (not the primes themselves) and any more that you have the patience for. \n\nWhen testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty.\n\n;Note\nIt can be shown (see talk page) that ''(2^p + 1)/3'' is always integral if ''p'' is odd. So there's no need to check for that prior to checking for primality.\n\n;References\n\n* Wikipedia - Wagstaff prime\n* OEIS:A000979 - Wagstaff primes\n\n", "solution": "require 'prime'\nrequire 'gmp'\n\nwagstaffs = Enumerator.new do |y|\n odd_primes = Prime.each\n odd_primes.next #skip 2\n loop do\n p = odd_primes.next\n candidate = (2 ** p + 1)/3\n y << [p, candidate] unless GMP::Z.new(candidate).probab_prime?.zero?\n end\nend\n\n10.times{puts \"%5d - %s\" % wagstaffs.next}\n14.times{puts \"%5d\" % wagstaffs.next.first}\n"} {"title": "Water collected between towers", "language": "Ruby", "task": "In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, \ncompletely filling all convex enclosures in the chart with water. \n\n \n9 ## 9 ## \n8 ## 8 ## \n7 ## ## 7 #### \n6 ## ## ## 6 ###### \n5 ## ## ## #### 5 ########## \n4 ## ## ######## 4 ############ \n3 ###### ######## 3 ############## \n2 ################ ## 2 ##################\n1 #################### 1 ####################\n \n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n\nSee, also:\n\n* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.\n\n\n\n", "solution": "def a(array)\nn=array.length\nleft={}\nright={}\nleft[0]=array[0]\ni=1\nloop do\n break if i >=n\nleft[i]=[left[i-1],array[i]].max\n i += 1 \nend\nright[n-1]=array[n-1]\ni=n-2\nloop do \nbreak if i<0\n right[i]=[right[i+1],array[i]].max\ni-=1\nend\ni=0\nwater=0\nloop do\nbreak if i>=n\nwater+=[left[i],right[i]].min-array[i]\ni+=1\nend\nputs water\nend\n\na([ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ])\na([ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ])\na([ 5, 5, 5, 5 ])\na([ 5, 6, 7, 8 ])\na([ 8, 7, 7, 6 ])\na([ 6, 7, 10, 7, 6 ])\nreturn"} {"title": "Weird numbers", "language": "Ruby", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* MathWorld: weird number\n\n", "solution": "def divisors(n)\n divs = [1]\n divs2 = []\n\n i = 2\n while i * i <= n\n if n % i == 0 then\n j = (n / i).to_i\n divs.append(i)\n if i != j then\n divs2.append(j)\n end\n end\n\n i = i + 1\n end\n\n divs2 += divs.reverse\n return divs2\nend\n\ndef abundant(n, divs)\n return divs.sum > n\nend\n\ndef semiperfect(n, divs)\n if divs.length > 0 then\n h = divs[0]\n t = divs[1..-1]\n if n < h then\n return semiperfect(n, t)\n else\n return n == h || semiperfect(n - h, t) || semiperfect(n, t)\n end\n else\n return false\n end\nend\n\ndef sieve(limit)\n w = Array.new(limit, false)\n i = 2\n while i < limit\n if not w[i] then\n divs = divisors(i)\n if not abundant(i, divs) then\n w[i] = true\n elsif semiperfect(i, divs) then\n j = i\n while j < limit\n w[j] = true\n j = j + i\n end\n end\n end\n i = i + 2\n end\n return w\nend\n\ndef main\n w = sieve(17000)\n count = 0\n max = 25\n print \"The first %d weird numbers:\\n\" % [max]\n n = 2\n while count < max\n if not w[n] then\n print n, \" \"\n count = count + 1\n end\n n = n + 2\n end\n print \"\\n\"\nend\n\nmain()"} {"title": "Word frequency", "language": "Ruby", "task": "Given a text file and an integer '''n''', print/display the '''n''' most\ncommon words in the file (and the number of their occurrences) in decreasing frequency.\n\n\nFor the purposes of this task:\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a ''letter'' is. \n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like '''well-dressed''' as either one word or two. \n* The word '''it's''' could also be one or two words as you see fit. \n* You may also choose not to support non US-ASCII characters. \n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences. \n* Treat '''color''' and '''colour''' as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*McIlroy's program\n\n\n\n\n", "solution": "class String\n def wc\n n = Hash.new(0)\n downcase.scan(/[A-Za-z\u00c0-\u00ff]+/) { |g| n[g] += 1 }\n n.sort{|n,g| n[1]<=>g[1]}\n end\nend\n\nopen('135-0.txt') { |n| n.read.wc[-10,10].each{|n| puts n[0].to_s+\"->\"+n[1].to_s} }\n"} {"title": "Word frequency", "language": "Ruby 2.7", "task": "Given a text file and an integer '''n''', print/display the '''n''' most\ncommon words in the file (and the number of their occurrences) in decreasing frequency.\n\n\nFor the purposes of this task:\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a ''letter'' is. \n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like '''well-dressed''' as either one word or two. \n* The word '''it's''' could also be one or two words as you see fit. \n* You may also choose not to support non US-ASCII characters. \n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences. \n* Treat '''color''' and '''colour''' as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*McIlroy's program\n\n\n\n\n", "solution": "RE = /[[:alpha:]]+/\ncount = open(\"135-0.txt\").read.downcase.scan(RE).tally.max_by(10, &:last)\ncount.each{|ar| puts ar.join(\"->\") }\n"} {"title": "Word ladder", "language": "Ruby from Raku", "task": "Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.\n\nOnly one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.\n\nDemonstrate the following:\n\nA boy can be made into a man: boy -> bay -> ban -> man\n\nWith a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady\n\nA john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane \n\nA child can not be turned into an adult.\n\nOptional transpositions of your choice.\n\n\n\n", "solution": "require \"set\"\n\nWords = File.open(\"unixdict.txt\").read.split(\"\\n\").\n group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }.\n to_h\n\ndef word_ladder(from, to)\n raise \"Length mismatch\" unless from.length == to.length\n sized_words = Words[from.length]\n work_queue = [[from]]\n used = Set.new [from]\n while work_queue.length > 0\n new_q = []\n work_queue.each do |words|\n last_word = words[-1]\n new_tails = Enumerator.new do |enum|\n (\"a\"..\"z\").each do |replacement_letter|\n last_word.length.times do |i|\n new_word = last_word.clone\n new_word[i] = replacement_letter\n next unless sized_words.include? new_word and\n not used.include? new_word\n enum.yield new_word\n used.add new_word\n return words + [new_word] if new_word == to\n end\n end\n end\n new_tails.each do |t|\n new_q.push(words + [t])\n end\n end\n work_queue = new_q\n end\nend\n\n[%w, %w, %w, %w].each do |from, to|\n if ladder = word_ladder(from, to)\n puts ladder.join \" \u2192 \"\n else\n puts \"#{from} into #{to} cannot be done\"\n end\nend"} {"title": "Word wrap", "language": "Ruby", "task": "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "class String\n def wrap(width)\n txt = gsub(\"\\n\", \" \")\n para = []\n i = 0\n while i < length \n j = i + width\n j -= 1 while j != txt.length && j > i + 1 && !(txt[j] =~ /\\s/)\n para << txt[i ... j]\n i = j + 1\n end\n para\n end\nend\n\ntext = <= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first '''30''' Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* Greatest common divisor.\n:* Plot coordinate pairs.\n\n\n;See also:\n:* The OEIS entry: A098550 The Yellowstone permutation.\n:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "def yellow(n)\n a = [1, 2, 3]\n b = { 1 => true, 2 => true, 3 => true }\n i = 4\n while n > a.length\n if !b[i] && i.gcd(a[-1]) == 1 && i.gcd(a[-2]) > 1\n a << i\n b[i] = true\n i = 4\n end\n i += 1\n end\n a\nend\n\np yellow(30)"} {"title": "Zeckendorf number representation", "language": "Ruby", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "def zeckendorf\n return to_enum(__method__) unless block_given?\n x = 0\n loop do\n bin = x.to_s(2)\n yield bin unless bin.include?(\"11\") \n x += 1\n end\nend\n\nzeckendorf.take(21).each_with_index{|x,i| puts \"%3d: %8s\"% [i, x]}"} {"title": "Zeckendorf number representation", "language": "Ruby from Python", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "def zeckendorf(n)\n return 0 if n.zero?\n fib = [1,2]\n fib << fib[-2] + fib[-1] while fib[-1] < n\n dig = \"\"\n fib.reverse_each do |f|\n if f <= n\n dig, n = dig + \"1\", n - f\n else\n dig += \"0\"\n end\n end\n dig.to_i\nend\n\nfor i in 0..20\n puts '%3d: %8d' % [i, zeckendorf(i)]\nend"} {"title": "Zeckendorf number representation", "language": "Ruby from Crystal", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "def zeckendorf(n)\n 0.step.lazy.map { |x| x.to_s(2) }.reject { |z| z.include?(\"11\") }.first(n)\nend\n\nzeckendorf(21).each_with_index{ |x,i| puts \"%3d: %8s\"% [i, x] }\n"} {"title": "Zero to the zero power", "language": "Ruby", "task": "Some computer programming languages are not exactly consistent (with other computer programming languages) \nwhen ''raising zero to the zeroth power'': 00\n\n\n;Task:\nShow the results of raising zero to the zeroth power.\n\n\nIf your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like:\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n\n'''Show the result here.'''\nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation. \n\n\n;See also:\n* The Wiki entry: Zero to the power of zero. \n* The Wiki entry: Zero to the power of zero: History.\n* The MathWorld(tm) entry: exponent laws.\n** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1.\n* The OEIS entry: The special case of zero to the zeroth power\n\n", "solution": "require 'bigdecimal'\n\n[0, 0.0, Complex(0), Rational(0), BigDecimal(\"0\")].each do |n|\n printf \"%10s: ** -> %s\\n\" % [n.class, n**n]\nend"} {"title": "Zhang-Suen thinning algorithm", "language": "Ruby", "task": "This is an algorithm used to thin a black and white i.e. one bit per pixel images. \n\nFor example, with an input image of:\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \nIt produces the thinned output:\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n\n;Algorithm:\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours. \n\nThe neighbours are, in order, arranged as:\n\n\n P9 P2 P3 \n P8 P1 P4 \n P7 P6 P5 \n\n\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\n\n;Step 1:\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\n\n;Step 2:\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and '''P8''' is white\n* (4) At least one of '''P2''' and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\n\n;Iteration:\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\n\n;Task:\n# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. \n\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n\n;Reference:\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen\n\n", "solution": "class ZhangSuen\n NEIGHBOUR8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] # 8 neighbors\n CIRCULARS = NEIGHBOUR8 + [NEIGHBOUR8.first] # P2, ... P9, P2\n def initialize(str, black=\"#\")\n s1 = str.each_line.map{|line| line.chomp.each_char.map{|c| c==black ? 1 : 0}}\n s2 = s1.map{|line| line.map{0}}\n xrange = 1 ... s1.size-1\n yrange = 1 ... s1[0].size-1\n printout(s1)\n begin\n @r = 0\n xrange.each{|x| yrange.each{|y| s2[x][y] = s1[x][y] - zs(s1,x,y,1)}} # Step 1\n xrange.each{|x| yrange.each{|y| s1[x][y] = s2[x][y] - zs(s2,x,y,0)}} # Step 2\n end until @r == 0\n printout(s1)\n end\n def zs(ng,x,y,g)\n return 0 if ng[x][y] == 0 or # P1\n (ng[x-1][y] + ng[x][y+1] + ng[x+g][y-1+g]) == 3 or # P2, P4, P6/P8\n (ng[x-1+g][y+g] + ng[x+1][y] + ng[x][y-1]) == 3 # P4/P2, P6, P8\n bp1 = NEIGHBOUR8.inject(0){|res,(i,j)| res += ng[x+i][y+j]} # B(P1)\n return 0 if bp1 < 2 or 6 < bp1\n ap1 = CIRCULARS.map{|i,j| ng[x+i][y+j]}.each_cons(2).count{|a,b| a