task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#PicoLisp
PicoLisp
(and (call 'sh "-c" (pack "dialog \ --inputbox 'Input a string' 8 60 \ --inputbox 'Input a number' 8 20 \ 2>" (tmp "dlg") ) ) (split (in (tmp "dlg") (line)) "^I") (cons (pack (car @)) (format (cadr @))) )
Give a code snippet in #PicoLisp In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#ACL2
ACL2
(defun hailstone (len) (loop for x = len then (if (evenp x) (/ x 2) (+ 1 (* 3 x))) collect x until (= x 1)))   ;; Must be tail recursive (defun max-hailstone-start (limit mx curr) (declare (xargs :mode :program)) (if (zp limit) ...
Give a code snippet in #ACL2 The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Avail
Avail
For each i from 10 to 0 by -1 do [Print: “i” ++ "\n";];
Give a code snippet in #Avail Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#IS-BASIC
IS-BASIC
100 PROGRAM "Letters.bas" 110 NUMERIC LETT(65 TO 90) 120 FOR I=65 TO 90 130 LET LETT(I)=0 140 NEXT 150 LET EOF=0 160 OPEN #1:"list.txt" 170 WHEN EXCEPTION USE IOERROR 180 DO 190 GET #1:A$ 200 LET A$=UCASE$(A$) 210 IF A$>="A" AND A$<="Z" THEN LET LETT(ORD(A$))=LETT(ORD(A$))+1 220 LOOP UNTIL EOF 230 END...
Give a code snippet in #IS-BASIC Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#BBC_BASIC
BBC BASIC
total% = 10000 FOR trial% = 1 TO total% prize_door% = RND(3) : REM. The prize is behind this door guess_door% = RND(3) : REM. The contestant guesses this door IF prize_door% = guess_door% THEN REM. The contestant guessed right, reveal either of the others reveal_d...
Give a code snippet in #BBC_BASIC Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
shuffle[deck_] := Apply[Riffle, TakeDrop[deck, Length[deck]/2]]; shuffleCount[n_] := Block[{count=0}, NestWhile[shuffle, shuffle[Range[n]], (count++; OrderedQ[#] )&];count]; Map[shuffleCount, {8, 24, 52, 100, 1020, 1024, 10000}]
Give a code snippet in #Mathematica.2FWolfram_Language A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ ...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#Kotlin
Kotlin
// version 1.1.4-3   import java.util.Random import java.io.File   val r = Random() val rr = Random() // use a separate generator for shuffles val ls = System.getProperty("line.separator")   var lower = "abcdefghijklmnopqrstuvwxyz" var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" var digit = "0123456789" var other = """!"#$%...
Give a code snippet in #Kotlin Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-....
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Groovy
Groovy
println (('the three truths' =~ /th/).count) println (('ababababab' =~ /abab/).count) println (('abaabba*bbaba*bbab' =~ /a*b/).count) println (('abaabba*bbaba*bbab' =~ /a\*b/).count)
Give a code snippet in #Groovy Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#Io
Io
withRange := method( a, z, Range clone setRange(a,z) ) sorted := withRange(1,9) asList numbers := sorted clone shuffle while( numbers==sorted, numbers = numbers shuffle)   steps :=0 stdin := File standardInput while( numbers != sorted, writeln(numbers join(" ")) write("Reverse how many? ") flipcount :...
Give a code snippet in #Io Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score...
christopher/rosetta-code
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Ruby
Ruby
def juggler(k) = k.even? ? Integer.sqrt(k) : Integer.sqrt(k*k*k)   (20..39).chain([113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915]).each do |k| k1 = k l = h = i = 0 until k == 1 do h, i = k, l if k > h l += 1 k = juggler(k) end if k1 < 40 then puts "#{k1}: l[...
Give a code snippet in #Ruby Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Java
Java
public class MagicSquare {   public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1...
Give a code snippet in #Java A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers ...
christopher/rosetta-code
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext...
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO;   --This package is for the delay. with Ada.Calendar; use Ada.Calendar;   --This package adds sound with Ada.Characters.Latin_1;   procedure Main is   begin   Put_Line ("Hello, this is 60 BPM");   loop   Ada.Text_IO.Put (Ada.Characters.Latin_1.BEL); delay 0.9;...
Give a code snippet in #Ada The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production ...
christopher/rosetta-code
http://rosettacode.org/wiki/ISBN13_check_digit
ISBN13 check digit
Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:   978-1734314502       (good)   ...
#Modula-2
Modula-2
MODULE ISBN; FROM InOut IMPORT WriteString, WriteLn; FROM Strings IMPORT Length;   PROCEDURE validISBN(s: ARRAY OF CHAR): BOOLEAN; VAR total, i, length: CARDINAL; BEGIN total := 0; length := Length(s); IF (length # 14) OR (s[3] # '-') THEN RETURN FALSE; END; FOR i := 0 TO length-1 DO ...
Give a code snippet in #Modula-2 Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Tcl
Tcl
proc div_check {x y} { if {[catch {expr {$x/$y}} result] == 0} { puts "valid division: $x/$y=$result" } else { if {$result eq "divide by zero"} { puts "caught division by zero: $x/$y -> $result" } else { puts "caught another error: $x/$y -> $result" } ...
Give a code snippet in #Tcl Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
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. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#C
C
#include "stdio.h"   typedef struct Range { int start, end, sum; } Range;   Range maxSubseq(const int sequence[], const int len) { int maxSum = 0, thisSum = 0, i = 0; int start = 0, end = -1, j;   for (j = 0; j < len; j++) { thisSum += sequence[j]; if (thisSum < 0) { i = j + ...
Give a code snippet in #C 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. An empty subsequence is considered to have the sum of   0;   thus if all elements are nega...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Raku
Raku
class Animal {} class Dog is Animal {} class Cat is Animal {} class Lab is Dog {} class Collie is Dog {}   say Collie.^parents; # undefined type object say Collie.new.^parents; # instantiated object
Give a code snippet in #Raku This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types....
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#FreeBASIC
FreeBASIC
#define NAN 0.0/0.0 'dot product of different-dimensioned vectors is no more defined than 0/0   function dot( a() as double, b() as double ) as double if ubound(a)<>ubound(b) then return NAN dim as uinteger i dim as double dp = 0.0 for i = 0 to ubound(a) dp += a(i)*b(i) next i retur...
Give a code snippet in #FreeBASIC Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#SenseTalk
SenseTalk
put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]   put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]   to handle customMedian of list sort list if the number of items in list is an even n...
Give a code snippet in #SenseTalk Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle val...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#XPL0
XPL0
real B1, B2, Ang; [Text(0, " Bearing 1 Bearing 2 Difference"); loop [B1:= RlIn(1); B2:= RlIn(1); Ang:= B2 - B1; while Ang > 180. do Ang:= Ang - 360.; while Ang < -180. do Ang:= Ang + 360.; CrLf(0); RlOut(0, B1); ChOut(0, 9); RlOut(0, B2); ChOu...
Give a code snippet in #XPL0 Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#F.23
F#
  let getJuliaValues width height centerX centerY zoom maxIter = let initzx x = 1.5 * float(x - width/2) / (0.5 * zoom * float(width)) let initzy y = 1.0 * float(y - height/2) / (0.5 * zoom * float(height)) let calc y x = let rec loop i zx zy = if i=maxIter then 0 elif zx*zx + zy*zy >= 4.0 then i ...
Give a code snippet in #F.23 Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Visual_Basic_.NET
Visual Basic .NET
Console.WriteLine(Chr(97)) 'Prints a Console.WriteLine(Asc("a")) 'Prints 97
Give a code snippet in #Visual_Basic_.NET Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Uni...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Elixir
Elixir
defmodule Loops do def while(0), do: :ok def while(n) do IO.puts n while( div(n,2) ) end end   Loops.while(1024)
Give a code snippet in #Elixir Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwa...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Gema
Gema
Star Trek=@err{found a Star Trek reference\n}@abort
Give a code snippet in #Gema Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Plain_English
Plain English
Put "abcdef" into a string. Slap a rider on the string.
Give a code snippet in #Plain_English Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearl...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Elena
Elena
import extensions;   fibu(n) { int[] ac := new int[]{ 0,1 }; if (n < 2) { ^ ac[n] } else { for(int i := 2, i <= n, i+=1) { int t := ac[1]; ac[1] := ac[0] + ac[1]; ac[0] := t };   ^ ac[1] } }   public program() { ...
Give a code snippet in #Elena The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#PHP
PHP
  <?php   header("Content-Type: text/plain; charset=UTF-8");   $days = array( 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', );   $gifts = array( "A partridge in a pear tree", "Two turtle doves", "Three french hens", "Four ca...
Give a code snippet in #PHP Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations:...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Form 60, 40 Foo=Lambda Id=1 (m)->{ class Alfa { x, id Class: Module Alfa(.x, .id) {} } =Alfa(m, id) id++ }   Dim A(10)<<Foo(20) \\ for each arrayitem call Foo(20) ...
Give a code snippet in #M2000_Interpreter Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they ...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Haskell
Haskell
module ISINVerification2 where   import Data.Char (isUpper, isDigit, digitToInt)   verifyISIN :: String -> Bool verifyISIN isin = correctFormat isin && mod (oddsum + multiplied_even_sum) 10 == 0 where reverted = reverse $ convertToNumber isin theOdds = fst $ collectOddandEven reverted theEvens = snd $ c...
Give a code snippet in #Haskell An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the corre...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Wren
Wren
import "/dynamic" for Struct   var mPref = { "abe": [ "abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"], "bob": [ "cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"], "col": [ "hope", "eve", "abi", "dee", "bea", "fay",...
Give a code snippet in #Wren Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Oz
Oz
fun {CreateNewNode Value} node(prev:{NewCell _} next:{NewCell _} value:Value) end
Give a code snippet in #Oz Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creat...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Symsyn
Symsyn
  | parent ssx 'R child' wait 'childevent' 'child is running...' [] 'child will end...' [] post 'dieevent' delay 5000  
Give a code snippet in #Symsyn Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Lua
Lua
num_iterations = 9 f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 }   function Output( f, l ) io.write( l, ": " ) for i = 1, #f do local c if f[i] == 1 then c = '#' else c = '_' end io.write( c ) end print "" end   Output( f, 0 )   for l = 1, num_iterations do ...
Give a code snippet in #Lua Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current g...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#BASIC
BASIC
10 DEFINT A-Z 20 DIM E(1000) 30 FOR I=0 TO 999 40 FOR J=I-1 TO 0 STEP -1 50 IF E(J)=E(I) THEN E(I+1)=I-J: GOTO 80 60 NEXT J 70 E(I+1)=0 80 NEXT I 90 FOR I=0 TO 9: PRINT E(I);: NEXT 95 PRINT 100 FOR I=990 TO 999: PRINT E(I);: NEXT
Give a code snippet in #BASIC The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#D
D
import std.stdio, std.random, sdl.SDL;   void main() { SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); auto surface = SDL_SetVideoMode(320,240,8, SDL_DOUBLEBUF|SDL_HWSURFACE);   uint frameNumber, totalTime, lastTime; while (true) { SDL_LockSurface(surface); foreach (i; 0 .. surface.w * surface.h) (cast...
Give a code snippet in #D Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#C
C
#include <stdio.h>   typedef int year_t, month_t, week_t, day_t;   typedef struct{ year_t year; /* day_t year_day, */ month_t month; day_t month_day;/* week_t week, */ day_t week_day; } date_t;   const char *mon_fmt[] = {0, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", ...
Give a code snippet in #C Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   ...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Forth
Forth
  : crc/ ( n -- n ) 8 0 do dup 1 rshift swap 1 and if $edb88320 xor then loop ;   : crcfill 256 0 do i crc/ , loop ;   create crctbl crcfill   : crc+ ( crc n -- crc' ) over xor $ff and cells crctbl + @ swap 8 rshift xor ;   : crcbuf ( crc str len -- crc ) bounds ?do i c@ crc+ loop ;   $ffffffff s" The quick brown f...
Give a code snippet in #Forth Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the...
christopher/rosetta-code
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Python
Python
import Image, ImageFilter im = Image.open('image.ppm')   median = im.filter(ImageFilter.MedianFilter(3)) median.save('image2.ppm')
Give a code snippet in #Python The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make local numbers: ARRAY [STRING] do numbers := <<"MCMXC", "MMVIII", "MDCLXVI", -- 1990 2008 1666 "MMMCLIX", "MCMLXXVII", "MMX">> -- 3159 1977 2010 across numbers as ...
Give a code snippet in #Eiffel Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#Python
Python
import smtplib   def sendemail(from_addr, to_addr_list, cc_addr_list, subject, message, login, password, smtpserver='smtp.gmail.com:587'): header = 'From: %s\n' % from_addr header += 'To: %s\n' % ','.join(to_addr_list) header += 'Cc: %s\n' % ','.join(cc_addr_list) ...
Give a code snippet in #Python Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given....
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: combinations is array array integer;   const func combinations: comb (in array integer: arr, in integer: k) is func result var combinations: combResult is combinations.value; local var integer: x is 0; var integer: i is 0; var array integer: suffix is 0 times ...
Give a code snippet in #Seed7 Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp>   using std::cout; using std::endl; const int NumFlags = 24;   int main() { std::fstream file("readings.txt");   int badCount = 0; std::string...
Give a code snippet in #C.2B.2B This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or perso...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#Peloton
Peloton
<@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@> <@ OMT>From First to Last</@> <@ ITEFORSZELSTLIT>public holidays| <@ SAYLST>...</@><@ ACTMOVFWDLST>...</@> </@> <@ OMT>From Last to First (pointer is still at end of list)</@> <@ ITEFORSZELSTLIT>public holidays| <@ SAYLST>...</@><@ ACTM...
Give a code snippet in #Peloton Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#SQL_PL
SQL PL
  SET SERVEROUTPUT ON @   BEGIN DECLARE NMBR VARCHAR(100) DEFAULT '1'; DECLARE J SMALLINT DEFAULT 1;   CALL DBMS_OUTPUT.PUT_LINE(NMBR); WHILE (J < 10) DO BEGIN DECLARE I SMALLINT; DECLARE SIZE SMALLINT; DECLARE ACTUAL CHAR(1); DECLARE REPEAT CHAR(1); DECLARE RESULT VARCHAR(100); DECLARE TIMES SMALLINT...
Give a code snippet in #SQL_PL The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Haskell
Haskell
module Main where {- __ __ __ ___ ___ /\ \/\ \ /\ \ /\_ \ /\_ \ \ \ \_\ \ __ ____\ \ \/'\ __\//\ \ \//\ \ \ \ _ \ /'__`\ /',__\\ \ , < /'__`\\ \ \ \ \ \ \ \ \ \ \/\ \L\.\_/\__, `\\ \ \\`\ /\ __/ \_\ \_ \_\ \_ \ \_\ \_\ \__/....
Give a code snippet in #Haskell Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#C
C
  #include<stdlib.h> #include<stdio.h>   typedef struct{ int rows,cols; int** dataSet; }matrix;   matrix readMatrix(char* dataFile){ FILE* fp = fopen(dataFile,"r"); matrix rosetta; int i,j;   fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);   rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));   for(i=0;i...
Give a code snippet in #C Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algor...
#360_Assembly
360 Assembly
* Comb sort 23/06/2016 COMBSORT CSECT USING COMBSORT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " ...
Give a code snippet in #360_Assembly Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see co...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#TXR
TXR
;; Syntactic sugar for calling reduce-left (defmacro reduce-with ((acc init item sequence) . body) ^(reduce-left (lambda (,acc ,item) ,*body) ,sequence ,init))    ;; Macro similar to clojure's ->> and -> (defmacro opchain (val . ops) ^[[chain ,*[mapcar [iffi consp (op cons 'op)] ops]] ,val])   ;; Reduce integer to ...
Give a code snippet in #TXR There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Fortran
Fortran
MODULE SEMPERNOVIS !Keep it together. TYPE CITYSTAT !Define a compound data type. CHARACTER*28 NAME !Long enough? REAL POPULATION !Accurate enough. END TYPE CITYSTAT !Just two parts, but different types. TYPE(CITYSTAT) CITY(10) !Righto, I'll have some. DATA CITY/ !S...
Give a code snippet in #Fortran Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#JavaScript
JavaScript
var s1 = "Hello"; s1 += ", World!"; print(s1);   var s2 = "Goodbye"; // concat() returns the strings together, but doesn't edit existing string // concat can also have multiple parameters print(s2.concat(", World!"));
Give a code snippet in #JavaScript Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Rust
Rust
extern crate primal;   fn isqrt(n: usize) -> usize { (n as f64).sqrt() as usize }   fn is_semiprime(mut n: usize) -> bool { let root = isqrt(n) + 1; let primes1 = primal::Sieve::new(root); let mut count = 0;   for i in primes1.primes_from(2).take_while(|&x| x < root) { while n % i == 0 { ...
Give a code snippet in #Rust Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chos...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#EchoLisp
EchoLisp
  (struct Point ((real:x 0) (real:y 0))) (struct Circle ((real:x 0) (real:y 0) (real:r 1)))   (define-method (print Point:p) (printf "📌 [%d %d]" p.x p.y)) (define-method (print Circle:c) (printf "⭕️ center:[%d %d] radius:%d" c.x c.y c.r))   (print (Point 5 6)) → 📌 [5 6] (print (Circle 2 3 4)) → ⭕️ center:[2 3...
Give a code snippet in #EchoLisp Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Tcl
Tcl
  #!/usr/bin/env tclsh #   package require generator ;# from tcllib   namespace eval stern-brocot { proc generate {{count 100}} { set seq {1 1} set n 0 while {[llength $seq] < $count} { lassign [lrange $seq $n $n+1] a b lappend seq [expr {$a + $b}] $b in...
Give a code snippet in #Tcl For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member ...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#UNIX_Shell
UNIX Shell
epoch=$(date -d 'March 7 2009 7:30pm EST +12 hours' +%s) date -d @$epoch TZ=Asia/Shanghai date -d @$epoch
Give a code snippet in #UNIX_Shell Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Euphoria
Euphoria
integer idM, idF   function F(integer n) if n = 0 then return 1 else return n - call_func(idM,{F(n-1)}) end if end function   idF = routine_id("F")   function M(integer n) if n = 0 then return 0 else return n - call_func(idF,{M(n-1)}) end if end function   idM = r...
Give a code snippet in #Euphoria Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F (...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#zkl
zkl
"http%3A%2F%2Ffoo%20bar%2F".pump(String, // push each char through these fcns: fcn(c){ if(c=="%") return(Void.Read,2); return(Void.Skip,c) },// %-->read 2 chars else pass through fcn(_,b,c){ (b+c).toInt(16).toChar() }) // "%" (ignored) "3"+"1"-->0x31-->"1"
Give a code snippet in #zkl This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded fo...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#ALGOL_68
ALGOL 68
# declare some constants # INT limit = 100;   PROC doors = VOID: ( MODE DOORSTATE = BOOL; BOOL closed = FALSE; BOOL open = NOT closed; MODE DOORLIST = [limit]DOORSTATE;   DOORLIST the doors; FOR i FROM LWB the doors TO UPB the doors DO the doors[i]:=closed OD;   FOR i FROM LWB the doors TO UPB the doors D...
Give a code snippet in #ALGOL_68 There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6,...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
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). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#11l
11l
F truncate_file(name, length) I !fs:is_file(name) R 0B I length >= fs:file_size(name) R 0B fs:resize_file(name, length) R 1B
Give a code snippet in #11l 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). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating ...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Python
Python
# String masquerading as ppm file (version P3) import io ppmfileout = io.StringIO('')   def togreyscale(self): for h in range(self.height): for w in range(self.width): r, g, b = self.get(w, h) l = int(0.2126 * r + 0.7152 * g + 0.0722 * b) self.set(w, h, Colour(l, l, l))  ...
Give a code snippet in #Python Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion...
christopher/rosetta-code
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#PHP
PHP
  <?php   function piece_wise($iban_all_digits) {   $remainder = NULL; $slice = 9;   for ($i=0; $i<strlen($iban_all_digits); $i=$i+$slice) { if ($i>0) { $slice = 7; }   $part = $remainder . substr($iban_all_digits, $i, $slice); //echo "REMAINDER: " ....
Give a code snippet in #PHP This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() {   rand.Seed(time.Now().UnixNano())   var n int = 3 // Change to define board size var moves int = 0   a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } }   b := make([][]int,...
Give a code snippet in #Go The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move)....
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Clojure
Clojure
(ns test-project-intellij.core (:gen-class))   (defn cube [x] "Cube a number through triple multiplication" (* x x x))   (defn sum3 [[i j]] " [i j] -> i^3 + j^3" (+ (cube i) (cube j)))   (defn next-pair [[i j]] " Generate next [i j] pair of sequence (producing lower triangle pairs) " (if (< j i) [i ...
Give a code snippet in #Clojure A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#PostScript
PostScript
  /pythamean{ /x exch def /sum 0 def /prod 1 def /invsum 0 def /i 1 def   x{ /sum sum i add def /prod prod i mul def /invsum invsum i -1 exp add def /i i 1 add def }repeat (Arithmetic Mean : ) print sum x div = (Geometric Mean : ) print prod x -1 exp exp = (Harmonic Mean : ) print x invsum div = }def   10 pythamean  
Give a code snippet in #PostScript Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1}...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#Octave
Octave
% test a bit; lsb is 1 (like built-in bit* ops) function b = bittst(n, p) b = bitand(n, 2^(p-1)) > 0; endfunction   function f = Mfactor(p) % msb is the index of the first non-zero bit [b, msb] = max(bitand(p, 2 .^ [32:-1:1]) > 0); maxk = floor(sqrt(intmax()) / p); for k = 1 : maxk q = 2*p*k + 1; if ...
Give a code snippet in #Octave A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before ...
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#Tcl
Tcl
set circles { 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.2375743054 -0.2495892950 -0.3832854473 1.0845181219 1.7813504266 1.6178237031 0.8162655711 -0.1985249206 -0.8343333301 0.05...
Give a code snippet in #Tcl Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#PL.2FI
PL/I
declare WS widechar (13) initial ('Hello world.'); put ('Character length=', length (WS)); put skip list ('Byte length=', size(WS));   declare SM graphic (13) initial ('Hello world'); put ('Character length=', length(SM)); put skip list ('Byte length=', size(trim(SM)));
Give a code snippet in #PL.2FI Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme con...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#ALGOL_68
ALGOL 68
# find the n most common words in a file # # use the associative array in the Associate array/iteration task # # but with integer values # PR read "aArrayBase.a68" PR MODE AAKEY = STRING; MODE AAVALUE = INT; AAVALUE init element value = 0; # re...
Give a code snippet in #ALGOL_68 Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#REBOL
REBOL
rebol [ Title: "Mutual Recursion" URL: http://rosettacode.org/wiki/Mutual_Recursion References: [http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences] ]   f: func [ "Female." n [integer!] "Value." ] [either 0 = n [1][n - m f n - 1]]   m: func [ "Male." n [integer!] "Value."...
Give a code snippet in #REBOL Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Raku
Raku
2e2 # same as 200e0, 2e2, 200.0e0 and 2.0e2 6.02e23 -2e48 1e-9 1e0
Give a code snippet in #Raku Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/A...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Run_BASIC
Run BASIC
haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ") needle$ = "Zag Wally Bush Chicken"   while word$(needle$,i+1," ") <> "" i = i + 1 thisNeedle$ = word$(needle$,i," ") + " " j = instr(haystack$,thisNeedle$) k1 = 0 k = instr(haystack$,thisNeedle$,j+1) while k <> 0 k1 = k k...
Give a code snippet in #Run_BASIC Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needl...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Perl
Perl
use ntheory "is_semiprime"; for ([1..100], [1675..1681], [2,4,99,100,1679,5030,32768,1234567,9876543,900660121]) { print join(" ",grep { is_semiprime($_) } @$_),"\n"; }
Give a code snippet in #Perl Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chos...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#PicoLisp
PicoLisp
(de isin (Str) (let Str (mapcar char (chop Str)) (and (= 12 (length Str)) (<= 65 (car Str) 90) (<= 65 (cadr Str) 90) (luhn (pack (mapcar '((N) (- N (if (<= 48 N 57) 48 55)) ) Str ) ) ) ) ) ) ...
Give a code snippet in #PicoLisp An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the corr...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Visual_Basic
Visual Basic
  Sub catalan() Const n = 15 Dim t(n + 2) As Long Dim i As Integer, j As Integer t(1) = 1 For i = 1 To n For j = i + 1 To 2 Step -1 t(j) = t(j) + t(j - 1) Next j t(i + 1) = t(i) For j = i + 2 To 2 Step -1 t(j) = t(j) + t(j - 1) Next j ...
Give a code snippet in #Visual_Basic Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#EasyLang
EasyLang
data[] = [ 29 4 72 44 55 26 27 77 92 5 ] # func qsort left right . . while left < right swap data[(left + right) / 2] data[left] mid = left for i = left + 1 to right if data[i] < data[left] mid += 1 swap data[i] data[mid] . . swap data[left] data[mid] call qsort le...
Give a code snippet in #EasyLang Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method brenfordDeveation(nlist = Rexx[]) public static observed = 0 loop n_ over nlist d1 = n_.left(1) if d1 = 0 then iterat...
Give a code snippet in #NetRexx This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the firs...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#ALGOL_W
ALGOL W
begin  % strips block comments from a source  %  % the source is read from standard input and the result written to  %  % standard output, The comment start text is in cStart and the ending  %  % is in cEnd. ...
Give a code snippet in #ALGOL_W A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos shou...
christopher/rosetta-code
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#C
C
#include <stdio.h> #include <string.h> /* note that UID & GID are of type "int" */ typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t;   #define GECOS_FMT "%...
Give a code snippet in #C Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most usefu...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Arturo
Arturo
compose: function [f,g] -> return function [x].import:[f,g][ call f @[call g @[x]] ]   splitupper: compose 'split 'upper   print call 'splitupper ["done"]
Give a code snippet in #Arturo Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g ...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#Ring
Ring
  # Project: Attractive Numbers   decomp = [] nump = 0 see "Attractive Numbers up to 120:" + nl while nump < 120 decomp = [] nump = nump + 1 for i = 1 to nump if isPrime(i) and nump%i = 0 add(decomp,i) dec = nump/i while dec%i = 0 add(decomp,i) dec = dec/i end ...
Give a code snippet in #Ring A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#Yabasic
Yabasic
clear screen open window 300,100 backcolor 0, 0, 0 window origin "cc"   // Display digital clock sub digital_clock() local t$(1), void static as$   void = token(time$, t$(), "-")   if t$(3) <> as$ then draw_clock(t$(1), t$(2), t$(3)) as$ = t$(3) end if end sub   sub draw_clock(hour$,...
Give a code snippet in #Yabasic Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change eve...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Wren
Wren
/* keyboard_macros.wren */   var GrabModeAsync = 1 var Mod1Mask = 1 << 3 var KeyPress = 2   var XK_F6 = 0xffc3 var XK_F7 = 0xffc4   foreign class XEvent { construct new() {}   foreign eventType }   foreign class XDisplay { construct openDisplay(displayName) {}   foreign defaultRootWindow()   ...
Give a code snippet in #Wren Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#REBOL
REBOL
rebol []   horner: func [coeffs x] [ result: 0 foreach i reverse coeffs [ result: (result * x) + i ] return result ]   print horner [-19 7 -4 6] 3
Give a code snippet in #REBOL A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#BCPL
BCPL
get "libhdr" manifest $( limit = 100 $)   let start() be $( let flags = vec limit for i = 0 to limit do flags!i := false   for a = 0 to limit by 6 for b = a to limit by 9 for c = b to limit by 20 do flags!c := true   for i = limit to 0 by -1 unless flags!i ...
Give a code snippet in #BCPL Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNug...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#AutoHotkey
AutoHotkey
  #Include Gdip.ahk ; https://autohotkey.com/boards/viewtopic.php?f=6&t=6517 Width :=A_ScreenWidth, Height := A_ScreenHeight Gui, 1: +E0x20 +Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs Gui, 1: Show, NA hwnd1 := WinExist() OnExit, Exit   If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, G...
Give a code snippet in #AutoHotkey A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or t...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT SECTION check IF (n!=1) THEN n = STRINGS (n,":>/:") LOOP/CLEAR nr=n square=nr*nr n=APPEND (n,square) ENDLOOP n=SUM(n) r_table=QUOTES (n) BUILD R_TABLE/word/EXACT chk=r_table IF (seq.ma.chk) THEN status="next" ELSE seq=APPEND (seq,n) ENDIF RELEASE r_ta...
Give a code snippet in #TUSCRIPT From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endless...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Crystal
Crystal
if false puts "false" elsif nil puts "nil" elsif Pointer(Nil).new 0 puts "null pointer" elsif true && "any other value" puts "finally true!" end
Give a code snippet in #Crystal Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Vlang
Vlang
fn main() { println("1: 1") for i := 2; ; i++ { print("$i: ") mut x := '' for n, f := i, 2; n != 1; f++ { for m := n % f; m == 0; m = n % f { print('$x$f') x = "×" n /= f } } println('') } }
Give a code snippet in #Vlang Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would...
christopher/rosetta-code
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such th...
#FreeBASIC
FreeBASIC
  #include "isprime.bas"   function iswief( byval p as uinteger ) as boolean if not isprime(p) then return 0 dim as integer q = 1, p2 = p^2 while p>1 q=(2*q) mod p2 p = p - 1 wend if q=1 then return 1 else return 0 end function   for i as uinteger = 1 to 5000 if iswief(i) then pr...
Give a code snippet in #FreeBASIC This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at P...
#Perl
Perl
use strict; use warnings;   showoff( "Permutations", \&P, "P", 1 .. 12 ); showoff( "Combinations", \&C, "C", map $_*10, 1..6 ); showoff( "Permutations", \&P_big, "P", 5, 50, 500, 1000, 5000, 15000 ); showoff( "Combinations", \&C_big, "C", map $_*100, 1..10 );   sub showoff { my ($text, $code, $fname, @n) = @_; print ...
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia....
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#8086_Assembly
8086 Assembly
.model small ; 128k .exe file .stack 1024 ; load SP with 0400h .data ; no data segment needed   .code   start:   mov ax,@code mov ds,ax mov es,ax   mov si,offset TestString mov di,offset OutputRam   cld   compressRLE: lodsb cmp al,0 ;null te...
Give a code snippet in #8086_Assembly Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provid...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Julia
Julia
  function digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10) -1 < n && 1 < bs || throw(DomainError()) ds = n pers = 0 while bs <= ds ds = prod(digits(ds, bs)) pers += 1 end return (pers, ds) end  
Give a code snippet in #Julia The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Oforth
Oforth
16 "sqrt" asMethod perform
Give a code snippet in #Oforth Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#D
D
import std.stdio, std.conv, std.string;   struct PiDigits { immutable uint nDigits;   int opApply(int delegate(ref string /*chunk of pi digit*/) dg){ // Maximum width for correct output, for type ulong. enum size_t width = 9;   enum ulong scale = 10UL ^^ width; enum ulong initDig...
Give a code snippet in #D Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#C.23
C#
  using System; using System.Collections.Generic; using System.Text;   namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); }   private stati...
Give a code snippet in #C.23 Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PowerShell
PowerShell
Function BeadSort ( [Int64[]] $indata ) { if( $indata.length -gt 1 ) { $min = $indata[ 0 ] $max = $indata[ 0 ] for( $i = 1; $i -lt $indata.length; $i++ ) { if( $indata[ $i ] -lt $min ) { $min = $indata[ $i ] } if( $indata[ $i ] -gt $max ) { $max = $indata[ $i ] } } #Find the min & max...
Give a code snippet in #PowerShell Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Elixir
Elixir
iex(1)> Enum.to_list(?a .. ?z) 'abcdefghijklmnopqrstuvwxyz' iex(2)> Enum.to_list(?a .. ?z) |> List.to_string "abcdefghijklmnopqrstuvwxyz"
Give a code snippet in #Elixir Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Z80_Assembly
Z80 Assembly
TestArray_Metadata: byte 4,4 ;4 rows, 4 columns. TestArray: byte 0,1,2,3 byte 4,5,6,7 byte 8,9,10,11 byte 12,13,14,15   OutputArray_Metadata: byte 2,4 OutputArray: ds 8,0 ;16 bytes each equaling zero   FilterEvenValues: ld hl,TestArray_Metadata ld a,(hl) inc hl ld b,(hl) inc hl ;LD HL,TestA...
Give a code snippet in #Z80_Assembly Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Forth
Forth
\ Gforth 0.7.9_20211014   : fusc ( n -- n) \ input n -- output fusc(n) dup dup 0= swap 1 = or \ n = 0 or 1 if exit \ return n else dup 2 mod 0= \ test even if 2/ recurse \ even fusc(n)= fusc(n/2) else du...
Give a code snippet in #Forth Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition st...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Action.21
Action!
PROC Main() PrintE("All Atari 8-bit computers use little-endian word of 16-bits size.") RETURN
Give a code snippet in #Action.21 Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Phix
Phix
function is_happy(integer n) sequence seen = {} while n>1 do seen &= n integer k = 0 while n>0 do k += power(remainder(n,10),2) n = floor(n/10) end while n = k if find(n,seen) then return false end if end while r...
Give a code snippet in #Phix From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly i...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#SAS
SAS
  %macro step(); %sysfunc(round(%sysfunc(ranuni(0)))) %mend step;  
Give a code snippet in #SAS From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detec...
christopher/rosetta-code