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/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#SPL
SPL
d='JC5wcmludCgiZD0nIitkKyInOyIrJC5iNjRkZWNvZGUoZCkp';$.print("d='"+d+"';"+$.b64decode(d))  
Give a code snippet in #SPL A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   s...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Objeck
Objeck
class Chaocipher { L_ALPHABET : static : Char[]; R_ALPHABET : static : Char[];   function : Main(args : String[]) ~ Nil { L_ALPHABET := "HXUCZVAMDSLKPEFJRIGTWOBNYQ"->ToCharArray(); R_ALPHABET := "PTLNBQDEOYSFAVZKGJRIHWXUMC"->ToCharArray(); plainText := "WELLDONEISBETTERTHANWELLSAID"->ToCharArray();   ...
Give a code snippet in #Objeck Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and ther...
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Racket
Racket
  #lang racket   (define (fs f s) (map f s)) (define (f1 n) (* n 2)) (define (f2 n) (* n n))   (define fsf1 (curry fs f1)) (define fsf2 (curry fs f2))   (fsf1 '(0 1 2 3)) (fsf1 '(2 4 6 8)) (fsf2 '(0 1 2 3)) (fsf2 '(2 4 6 8))  
Give a code snippet in #Racket Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original functi...
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...
#Mercury
Mercury
:- module string_byte_length. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module list, string.   main(!IO) :- Words = ["møøse", "𝔘𝔫𝔦𝔠𝔬𝔡𝔢", "J\x332\o\x332\s\x332\e\x301\\x332\"], io.write_list(Words, "", write_length, !IO).   :- pred write_l...
Give a code snippet in #Mercury 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 co...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#PHP
PHP
function mergesort($arr){ if(count($arr) == 1 ) return $arr; $mid = count($arr) / 2; $left = array_slice($arr, 0, $mid); $right = array_slice($arr, $mid); $left = mergesort($left); $right = mergesort($right); return merge($left, $right); }   function merge($left, $right){ $res = array(); while (count($le...
Give a code snippet in #PHP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Delphi
Delphi
  ;; use the obvious methos (lib 'list) ; for (permutations) function   ;; input (define perms ' (ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB))   ;; generate all permutations (define all-perms (map list->string (permutations '(A B C D)))) → all-p...
Give a code snippet in #Delphi ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#PowerShell
PowerShell
  function When-Condition { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, Position=0)] [bool] $Test1,   [Parameter(Mandatory=$true, Position=1)] [bool] $Test2,   [Parameter(Mandatory=$true, Position=2)] [scriptblock] $Both,   ...
Give a code snippet in #PowerShell Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#uBasic.2F4tH
uBasic/4tH
For i = 1 To 100 ' Fill array with some values @(i-1) = i Next   Print FUNC(_binarySearch(50,0,99)) ' Now find value '50' End ' and prints its index     _binarySearch Param(3) ' value, start index, end index Local(1) ...
Give a code snippet in #uBasic.2F4tH A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#SPL
SPL
a2r(a)= r = "" n = [["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"],[1000,900,500,400,100,90,50,40,10,9,5,4,1]] > i, 1..13 > a!<n[i,2] r += n[i,1] a -= n[i,2] < < <= r .   t = [1990,2008,1666] > i, 1..#.size(t,1) #.output(t[i]," = ",a2r(t[i])) <
Give a code snippet in #SPL Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_sentence_from_book
Random sentence from book
Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too). Keep a...
#Python
Python
from urllib.request import urlopen import re from string import punctuation from collections import Counter, defaultdict import random     # The War of the Worlds, by H. G. Wells text_url = 'http://www.gutenberg.org/files/36/36-0.txt' text_start = 'No one would have believed'   sentence_ending = '.!?' sentence_pausing ...
Give a code snippet in #Python Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence te...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the widt...
#Forth
Forth
c-library m s" m" add-lib \c #include <math.h> c-function fnextafter nextafter r r -- r end-c-library   s" MAX-FLOAT" environment? drop fconstant MAX-FLOAT   : fstepdown ( F: r1 -- r2 ) MAX-FLOAT fnegate fnextafter ; : fstepup ( F: r1 -- r2 ) MAX-FLOAT fnextafter ;   : savef+ ( F: r1 r2 -- r3 r4 ) \ r4 <= r1+r2 <...
Give a code snippet in #Forth Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additiona...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#MATLAB
MATLAB
>> array = [1 2 3 4 5]   array =   1 2 3 4 5   >> arrayfun(@sin,array)   ans =   Columns 1 through 4   0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928   Column 5   -0.958924274663138   >> cellarray = {1,2,3,4,5}   cellarray =   [1] [2] [3] [4] ...
Give a code snippet in #MATLAB Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Brat
Brat
number = random 10   p "Guess a number between 1 and 10."   until { true? ask("Guess: ").to_i == number { p "Well guessed!"; true } { p "Guess again!" } }
Give a code snippet in #Brat Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#AutoHotkey
AutoHotkey
FileRead, inventory, xmlfile.xml   RegExMatch(inventory, "<item.*?</item>", item1) MsgBox % item1   pos = 1 While, pos := RegExMatch(inventory, "<price>(.*?)</price>", price, pos + 1) MsgBox % price1   While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1) names .= name . "`n" MsgBox % names
Give a code snippet in #AutoHotkey Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp St...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Logo
Logo
print reverse "cat  ; tac
Give a code snippet in #Logo Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Yabasic
Yabasic
  dim funcs$(10)   sub power2(i) return i * i end sub   for i = 1 to 10 funcs$(i) = "power2" next   for i = 1 to 10 print execute(funcs$(i), i) next  
Give a code snippet in #Yabasic Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#Ruby
Ruby
require 'win32/eventlog' logger = Win32::EventLog.new logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry")
Give a code snippet in #Ruby Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Picat
Picat
go => ["1223334444", "Rosetta Code is the best site in the world!", "1234567890abcdefghijklmnopqrstuvwxyz", "Picat is fun"].map(entropy).println(), nl.   % probabilities of each element/character in L entropy(L) = Entropy => Len = L.length, Occ = new_map(), % # of occurrences foreach(E in L) Occ...
Give a code snippet in #Picat Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), ...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Lingo
Lingo
-- Create a ByteArray of 100 Kb (pre-filled with 0 bytes) ba = byteArray(102400)   -- Lingo uses garbage-collection, so allocated memory is released when no more references exist. -- For the above variable ba, this can be achieved by calling: ba = VOID
Give a code snippet in #Lingo Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#D
D
import std.stdio, std.algorithm, std.functional;   string[][] sortTable(string[][] table, in bool function(string[],string[]) ordering=null, in int column = 0, in bool reverse = false) { if (ordering is null) table.schwartzSort!(row => row[colum...
Give a code snippet in #D Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicog...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equation important in navigation, g...
#Java
Java
public class Haversine { public static final double R = 6372.8; // In kilometers public static double haversine(double lat1, double lon1, double lat2, double lon2) { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); lat1 = Math.toRadians(lat1); ...
Give a code snippet in #Java This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equat...
christopher/rosetta-code
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#PureBasic
PureBasic
Macro Tell(Mutex, Message) ; Make a macro to easy send info back to main thread LockMutex(Mutex) LastElement(Queue()) AddElement(Queue()) Queue() = Message SignalSemaphore(Semaphore) UnlockMutex(Mutex) EndMacro   ;Set up a data structure to pass needed info into the threads Structure Thread_Paramete...
Give a code snippet in #PureBasic The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Oforth
Oforth
Channel new [ ] over send drop const: StdValues   : stddev(x) | l | StdValues receive x + dup ->l StdValues send drop #qs l map sum l size asFloat / l avg sq - sqrt ;
Give a code snippet in #Oforth Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the func...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#DWScript
DWScript
  var dog : String;   dog := 'Benjamin'; Dog := 'Samba'; DOG := 'Bernie';   PrintLn('There is just one dog named ' + dog);
Give a code snippet in #DWScript Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin,...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Scala
Scala
val wordsAll = scala.io.Source. fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"). getLines().map(_.toLowerCase).toIndexedSeq     /** * Given a sequence of lower-case words return a sub-sequence * of matches containing the word and its reverse if the two * words are different. */ def semordn...
Give a code snippet in #Scala A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the tota...
christopher/rosetta-code
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Bracmat
Bracmat
myVar=immutable (m=mutable) immutable; changed:?(myVar.m); lst$myVar  
Give a code snippet in #Bracmat Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
christopher/rosetta-code
http://rosettacode.org/wiki/Modified_random_distribution
Modified random distribution
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand...
#Go
Go
package main   import ( "fmt" "math" "math/rand" "strings" "time" )   func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } }   func commatize(n int) string { s...
Give a code snippet in #Go Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following a...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Objeck
Objeck
use Collection.Generic; use System.Matrix;   class RPNParser { @stk : Stack<IntHolder>; @digits : List<IntHolder>;   function : Main(args : String[]) ~ Nil { digits := List->New()<IntHolder>; "Make 24 with the digits: "->Print(); for(i := 0; i < 4; i += 1;) { n : Int := Int->Random(1, 9); ...
Give a code snippet in #Objeck The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four d...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Haskell
Haskell
digsum :: Integral a => a -> a -> a digsum base = f 0 where f a 0 = a f a n = f (a + r) q where (q, r) = n `quotRem` base   main :: IO () main = print $ digsum 16 255 -- "FF": 15 + 15 = 30
Give a code snippet in #Haskell Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Trith
Trith
true ["yes" print] ["no" print] branch
Give a code snippet in #Trith Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common ...
christopher/rosetta-code
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Tcl
Tcl
proc encoder int { set u [format %c $int] set bytes {} foreach byte [split [encoding convertto utf-8 $u] ""] { lappend bytes [format %02X [scan $byte %c]] } return $bytes } proc decoder bytes { set str {} foreach byte $bytes { append str [format %c [scan $byte %x]] } return [encod...
Give a code snippet in #Tcl As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes repre...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Prolog
Prolog
:- use_module(library(simplex)).   % tuples (name, Explantion, Value, weights, volume). knapsack :- L =[( panacea, 'Incredible healing properties', 3000, 0.3, 0.025), ( ichor, 'Vampires blood', 1800, 0.2, 0.015), ( gold , 'Shiney shiney', 2500, 2.0, 0.002)],   gen_state(S0), l...
Give a code snippet in #Prolog A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#zkl
zkl
s:=""; // or s:=String, String is the object "" s.toBool() //-->False if (s) println("not empty")
Give a code snippet in #zkl Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_calendar
Mayan calendar
The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gregorian calendar. The Calendar R...
#zkl
zkl
var [const] sacred=T("Imix'","Ik'","Ak'bal","K'an","Chikchan","Kimi","Manik'","Lamat","Muluk","Ok", "Chuwen","Eb","Ben","Hix","Men","K'ib'","Kaban","Etz'nab'","Kawak","Ajaw"), civil=T("Pop","Wo'","Sip","Sotz'","Sek","Xul","Yaxk'in","Mol","Ch'en","Yax","Sak'","Keh", "Mak","K'ank'in","Muwan'","P...
Give a code snippet in #zkl The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gregor...
christopher/rosetta-code
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#MiniZinc
MiniZinc
  %Fraction Reduction. Nigel Galloway, September 5th., 2019 include "alldifferent.mzn"; include "member.mzn"; int: S; array [1..9] of int: Pn=[1,10,100,1000,10000,100000,1000000,10000000,100000000]; array [1..S] of var 1..9: Nz; constraint alldifferent(Nz); array [1..S] of var 1..9: Gz; constraint alldifferent(Gz); var...
Give a code snippet in #MiniZinc There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Delphi
Delphi
var P: PInteger; begin New(P); //Allocate some memory try If Assigned(P) Then //... begin P^ := 42; end; finally Dispose(P); //Release memory allocated by New end; end;
Give a code snippet in #Delphi
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#OCaml
OCaml
let a = (3.0, 4.0, 5.0) let b = (4.0, 3.0, 5.0) let c = (-5.0, -12.0, -13.0)   let string_of_vector (x,y,z) = Printf.sprintf "(%g, %g, %g)" x y z   let dot (a1, a2, a3) (b1, b2, b3) = (a1 *. b1) +. (a2 *. b2) +. (a3 *. b3)   let cross (a1, a2, a3) (b1, b2, b3) = (a2 *. b3 -. a3 *. b2, a3 *. b1 -. a1 *. b3, ...
Give a code snippet in #OCaml A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Sather
Sather
abstract class $EDIBLE is eat; end;   class FOOD < $EDIBLE is readonly attr name:STR; eat is #OUT + "eating " + self.name + "\n"; end; create(name:STR):SAME is res ::= new; res.name := name; return res; end; end;   class CAR is readonly attr name:STR; create(name:STR):SAME is res ::=...
Give a code snippet in #Sather Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Action.21
Action!
PROC Run(CHAR ARRAY code) BYTE i,a CHAR c   PrintF("Run ""%S""%E%E",code) a=0 FOR i=1 TO code(0) DO c=code(i) IF c='q OR c='Q THEN PrintE(code) ELSEIF c='h OR c='H THEN PrintE("Hello, world!") ELSEIF c='9 THEN PrintE("99 bottles here...") ELSEIF c='+ THEN a==+1 ...
Give a code snippet in #Action.21 Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Sidef
Sidef
func zodiac(year) { var animals = %w(Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig) var elements = %w(Wood Fire Earth Metal Water) var terrestrial_han = %w(子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥) var terrestrial_pinyin = %w(zĭ chŏu yín măo chén sì wŭ wèi shēn yŏu xū hài) var celestial_han = %w(甲 乙 丙 丁 戊...
Give a code snippet in #Sidef Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities result...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#C.23
C#
using System; using System.Text; using System.Collections.Generic;   public class TokenizeAStringWithEscaping { public static void Main() { string testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) { Console.WriteLine(...
Give a code snippet in #C.23 Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for split...
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...
#CLU
CLU
% Split a string based on a change of character split_on_change = iter (s: string) yields (string) part: string := "" for c: char in string$chars(s) do if ~string$empty(part) cand part[string$size(part)] ~= c then yield(part) part := "" end part := part ...
Give a code snippet in #CLU 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Julia
Julia
using Primes   eulerphi(n) = (r = one(n); for (p,k) in factor(abs(n)) r *= p^(k-1)*(p-1) end; r)   const phicache = Dict{Int, Int}()   cachedphi(n) = (if !haskey(phicache, n) phicache[n] = eulerphi(n) end; phicache[n])   function perfecttotientseries(n) perfect = Vector{Int}() i = 1 while length(perfect) < ...
Give a code snippet in #Julia Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Clojure
Clojure
(ns brainfuck)   (def ^:dynamic *input*)   (def ^:dynamic *output*)   (defrecord Data [ptr cells])   (defn inc-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] inc))))   (defn dec-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] dec))))   (defn inc-cell [next-cmd] (fn [data] (next-...
Give a code snippet in #Clojure Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly impl...
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 ) ) , ...
#Jsish
Jsish
/* Mutual recursion, is jsish */ function f(num):number { return (num === 0) ? 1 : num - m(f(num - 1)); } function m(num):number { return (num === 0) ? 0 : num - f(m(num - 1)); }   function range(n=10, start=0, step=1):array { var a = Array(n).fill(0); for (var i in a) a[i] = start+i*step; return a; }   var a ...
Give a code snippet in #Jsish 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/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = "thisisatest"; b = "testing123testing"; LongestCommonSequence[a, b]
Give a code snippet in #Mathematica.2FWolfram_Language Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]…...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Tcl
Tcl
package require Tcl 8.5   expr {1.0 / 0} ;# ==> Inf expr {-1.0 / 0} ;# ==> -Inf expr {inf} ;# ==> Inf expr {1 / 0} ;# ==> "divide by zero" error; Inf not part of range of integer division
Give a code snippet in #Tcl Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, r...
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...
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   placesList = [String - "UK London", "US New York" - , "US Boston", "US Washington" - , "UK Washington", "US Birmingham" - , "UK Birmingham", "UK Boston" - ] sortedList = combSort(String[] Arrays.copyOf...
Give a code snippet in #NetRexx 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...
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
#PowerShell
PowerShell
  $method = ([Math] | Get-Member -MemberType Method -Static | Where-Object {$_.Definition.Split(',').Count -eq 1} | Get-Random).Name $number = (1..9 | Get-Random) / 10 $result = [Math]::$method($number) $output = [PSCustomObject]@{ Method = $method Number = $number Result = $result }   $output | Format-List...
Give a code snippet in #PowerShell 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/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#J
J
brtr=:4 :0 seed=. ?x clip=. 0 >. (<:x) <."1 ] near=. [: clip +"1/&(,"0/~i:1) p=.i.0 2 mask=. 1 (<"1 near seed)} x$0 field=.1 (<seed)} x$0 for.i.y do. p=. clip (p +"1 <:?3$~$p),?x b=.(<"1 p) { mask fix=. b#p if.#fix do. NB. if. works around j602 bug: 0(0#a:)}i.0 0 p=. (-.b)# p m...
Give a code snippet in #J Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "s...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Wolfram_Language
Wolfram Language
Print["Hello world!"]
Give a code snippet in #Wolfram_Language Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Stand...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#AutoHotkey
AutoHotkey
  URL := "https://sourceforge.net/" WININET_Init() msgbox % html := UrlGetContents(URL) WININET_UnInit() return #include urlgetcontents.ahk #include wininet.ahk  
Give a code snippet in #AutoHotkey Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Re...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Go
Go
package main   import ( "fmt" "math/big" )   var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}   const maxStack = 128   var ( tens, values [maxStack]big.Int bigTemp, answer = new(big.Int), new(big.Int) base, seenDepth int )   func addDigit(i int) { for d := 1; d < base; d++ { ...
Give a code snippet in #Go A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Le...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#BASIC256
BASIC256
f = freefile filename$ = "file.txt"   open f, filename$   while not eof(f) print readline(f) end while close f end
Give a code snippet in #BASIC256 Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Haskell
Haskell
import System.Exit (die) import Control.Monad (mapM_)   main = do putStrLn "Please enter temperature in kelvin: " input <- getLine let kelvin = read input if kelvin < 0.0 then die "Temp cannot be negative" else mapM_ putStrLn $ convert kelvin   convert :: Double -> [String] convert n = zipWith (++) ...
Give a code snippet in #Haskell There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.1...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Lua
Lua
local find, format = string.find, string.format local function printf(fmt, ...) print(format(fmt,...)) end   local pattern = '(.).-%1' -- '(.)' .. '.-' .. '%1'   function report_dup_char(subject) local pos1, pos2, char = find(subject, pattern)   local prefix = format('"%s" (%d)', subject, #subject) if pos1 ...
Give a code snippet in #Lua Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Arturo
Arturo
factorial: function [n]-> product 1..n   lah: function [n,k][ if k=1 -> return factorial n if k=n -> return 1 if k>n -> return 0 if or? k<1 n<1 -> return 0 return (((factorial n)*factorial n-1) / ((factorial k) * factorial k-1)) / factorial n-k ]   print @["n/k"] ++ map to [:string] 1..12 's -> pad ...
Give a code snippet in #Arturo Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly...
christopher/rosetta-code
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#C
C
#include <stdio.h> #include <math.h> #include <unistd.h>   const char *shades = ".:!*oe&#%@";   double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; }   double dot(double *x, double *y) { double d = x[0]*y[0] + x[1...
Give a code snippet in #C Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name i...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Kotlin
Kotlin
fun main(args: Array<String>) { val a = intArrayOf(1, 2, 3, 4, 5) println("Array  : ${a.joinToString(", ")}") println("Sum  : ${a.reduce { x, y -> x + y }}") println("Difference  : ${a.reduce { x, y -> x - y }}") println("Product  : ${a.reduce { x, y -> x * y }}") println("Minimum...
Give a code snippet in #Kotlin Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Transd
Transd
#lang transd   MainModule : { _start: (lambda (lout "Police | Sanit. | Fire") (for i in Range(1 8) where (not (mod i 2)) do (for j in Range(1 8) where (neq i j) do (for k in Range(1 8) where (and (neq i k) (neq j k)) do (if (eq (+ i j k) 12) (lout i " "...
Give a code snippet in #Transd There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (d...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#MUMPS
MUMPS
SYSTIME NEW PH SET PH=$PIECE($HOROLOG,",",2) WRITE "The system time is ",PH\3600,":",PH\60#60,":",PH#60 KILL PH QUIT
Give a code snippet in #MUMPS Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   ...
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
#Kotlin
Kotlin
  {if true then YES else NO} -> YES {if false then YES else NO} -> NO  
Give a code snippet in #Kotlin 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/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   /* REXX *************************************************************** * 11.05.2013 Walter Pachl **********************************************************************/ runSample(arg) return   /** * Test for rep-strings * @param s_str a s...
Give a code snippet in #NetRexx Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at le...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#11l
11l
os:(‘pause’)
Give a code snippet in #11l Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Processing
Processing
void setup() { for (int i = 1; i <= 5; i++) { int count = 0; print("k = " + i + ": "); int n = 2; while (count < 10) { if (isAlmostPrime(i, n)) { count++; print(n + " "); } n++; } println(); } }   boolean isAlmostPrime(int k, int n) { if (countPrimeFactors...
Give a code snippet in #Processing A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#Nim
Nim
import os, rdstdin   var empty = true for f in walkDir(readLineFromStdin "directory: "): empty = false break echo empty
Give a code snippet in #Nim Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Phix
Phix
without js -- system_exec, file i/o constant tmp = "hostname.txt", cmd = iff(platform()=WINDOWS?"hostname":"uname -n") {} = system_exec(sprintf("%s > %s",{cmd,tmp}),4) string host = trim(get_text(tmp)) {} = delete_file(tmp) ?host
Give a code snippet in #Phix Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
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 ...
#TXR
TXR
(defun comb-n-m (n m) (comb (range* 0 n) m))   (put-line `3 comb 5 = @(comb-n-m 5 3)`)
Give a code snippet in #TXR 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i";   const func string: center (in string: stri, in integer: length) is return ("" lpad (length - length(stri)) div 2 <& stri) rpad length;   const proc: printCalendar (in integer: year, in integer: cols) is func local var time: date is time.value; var integer: d...
Give a code snippet in #Seed7 Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#Kotlin
Kotlin
import kotlin.math.max import kotlin.math.min   private const val EPS = 0.001 private const val EPS_SQUARE = EPS * EPS   private fun test(t: Triangle, p: Point) { println(t) println("Point $p is within triangle ? ${t.within(p)}") }   fun main() { var p1 = Point(1.5, 2.4) var p2 = Point(5.1, -3.1) va...
Give a code snippet in #Kotlin Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#PowerShell
PowerShell
'{0:00000.000}' -f 7.125
Give a code snippet in #PowerShell Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#FreeBASIC
FreeBASIC
' VERSION 16-03-2016 ' COMPILE WITH: FBC -S CONSOLE   ' TRUE/FALSE ARE BUILT-IN CONSTANTS SINCE FREEBASIC 1.04 ' BUT WE HAVE TO DEFINE THEM FOR OLDER VERSIONS. #IFNDEF TRUE #DEFINE FALSE 0 #DEFINE TRUE NOT FALSE #ENDIF   FUNCTION WD(M AS INTEGER, D AS INTEGER, Y AS INTEGER) AS INTEGER ' ZELLERISH ' 0 = ...
Give a code snippet in #FreeBASIC Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert 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 ...
#Raku
Raku
# Empty list sorts to the empty list multi quicksort([]) { () }   # Otherwise, extract first item as pivot... multi quicksort([$pivot, *@rest]) { # Partition. my $before := @rest.grep(* before $pivot); my $after := @rest.grep(* !before $pivot);   # Sort the partitions. flat quicksort($befor...
Give a code snippet in #Raku 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
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 |...
#Lasso
Lasso
local( number1 = integer(web_request -> param('number1')), number2 = integer(web_request -> param('number2')) )   #number1 < #number2 ? 'Number 1 is less than Number 2' | 'Number 1 is not less than Number 2' '<br />' #number1 == #number2 ? 'Number 1 is the same as Number 2' | 'Number 1 is not the same as Number 2' '<...
Give a code snippet in #Lasso 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q...
#Wren
Wren
import "/dynamic" for Enum import "/fmt" for Fmt import "/seq" for Lst import "/math" for Nums import "/sort" for Sort   var Direction = Enum.create("Direction", ["UP", "DOWN"])   // test also for 'Unknown' correction type var types = [ "Benjamini-Hochberg", "Benjamini-Yekutieli", "Bonferroni", "Hochberg", "Hol...
Give a code snippet in #Wren Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Julia
Julia
dict = Dict('a' => 97, 'b' => 98) # list keys/values # Dict{Char,Int64} with 2 entries: # 'b' => 98 # 'a' => 97   dict = Dict(c => Int(c) for c = 'a':'d') # dict comprehension # Dict{Char,Int64} with 4 entries: # 'b' => 98 # 'a' => 97 # 'd' => 100 # 'c' => 99   dict['é'] = 233; dict # add an element # Dict{...
Give a code snippet in #Julia Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#PARI.2FGP
PARI/GP
#!/usr/bin/perl do "include.pl"; # Utilize source from another file sayhello();
Give a code snippet in #PARI.2FGP Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Julia
Julia
i = zero(BigInt) # or i = big(0) while true println(i += 1) end
Give a code snippet in #Julia Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations li...
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { var n, e, d, bb, ptn, etn, dtn big.Int pt := "Rosetta Code" fmt.Println("Plain text: ", pt)   // a key set big enough to hold 16 bytes of plain text in // a single block (to simplify the example) and also big enough //...
Give a code snippet in #Go Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Euphoria
Euphoria
include sort.e   function compare_keys(sequence a, sequence b) return compare(a[1],b[1]) end function   constant fn = open("unixdict.txt","r") sequence words, anagrams object word words = {} while 1 do word = gets(fn) if atom(word) then exit end if word = word[1..$-1] -- truncate new-line ch...
Give a code snippet in #Euphoria When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words i...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Tcl
Tcl
string repeat "ha" 5 ;# => hahahahaha
Give a code snippet in #Tcl Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =>...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#BCPL
BCPL
  GET "libhdr"   LET sumdiv(n, d) = VALOF { LET m = n/d RESULTIS m*(m + 1)/2 * d }   LET sum3or5(n) = sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)   LET start() = VALOF { LET sum = 0 LET n = 1   FOR k = 1 TO 999 DO IF k MOD 3 = 0 | k MOD 5 = 0 THEN sum +:= k writef("The sum of the multipl...
Give a code snippet in #BCPL Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Common_Lisp
Common Lisp
(defun friday-before (year month day) (let* ((timestamp (encode-universal-time 0 0 12 day month year)) (weekday (nth 6 (multiple-value-list (decode-universal-time timestamp)))) (fri (- timestamp (* (+ (mod (+ weekday 2) 7) 1) 86400)))) (multiple-value-bind (_ _ _ d m y) (decode-universal-time fri) (l...
Give a code snippet in #Common_Lisp Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-2...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#PicoLisp
PicoLisp
(de ** (X N) # N th power of X (if (ge0 N) (let Y 1 (loop (when (bit? 1 N) (setq Y (* Y X)) ) (T (=0 (setq N (>> 1 N))) Y ) (setq X (* X X)) ) ) 0 ) )
Give a code snippet in #PicoLisp Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Vlang
Vlang
import rand import rand.seed const target = "METHINKS IT IS LIKE A WEASEL".bytes() const set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".bytes()       fn initialize() []u8 { rand.seed(seed.time_seed_array(2)) mut parent := []u8{len: target.len} for i in 0..parent.len { parent[i] = set[rand.intn(set.len) or {0}]...
Give a code snippet in #Vlang Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Lasso
Lasso
local(root = json_deserialize(curl('http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json')->result)) local(tasks = array, title = string, urltitle = string, thiscount = 0, totalex = 0) with i in #root->find('query')->find('categorymembers') do => ...
Give a code snippet in #Lasso task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'l...
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#Groovy
Groovy
class CutRectangle { private static int[][] dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]]   static void main(String[] args) { cutRectangle(2, 2) cutRectangle(4, 3) }   static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) { return }   int[...
Give a code snippet in #Groovy A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such path...
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...
#Action.21
Action!
PROC KnuthShuffle(BYTE ARRAY tab BYTE size) BYTE i,j,tmp   i=size-1 WHILE i>0 DO j=Rand(i+1) tmp=tab(i) tab(i)=tab(j) tab(j)=tmp i==-1 OD RETURN   BYTE FUNC IsSorted(BYTE ARRAY tab BYTE size) BYTE i   FOR i=0 TO size-2 DO IF tab(i)>tab(i+1) THEN RETURN (0) FI OD RETUR...
Give a code snippet in #Action.21 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. Th...
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 ...
#QB64_2
QB64
_DEFINE F AS _UNSIGNED _INTEGER64 CLS PRINT PRINT "Enter 40 to more easily see the difference in calculation speeds." PRINT INPUT "Enter n for Fibonacci(n): ", n PRINT PRINT " Analytic Method (Fastest): F("; LTRIM$(STR$(n)); ") ="; fA(n) PRINT "Iterative Method (Fast): F("; LTRIM$(STR$(n)); ") ="; fI(n) PRINT "Recur...
Give a code snippet in #QB64_2 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 ar...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Intercal
Intercal
bottles := method(i, if(i==0, return "no more bottles of beer") if(i==1, return "1 bottle of beer") "" .. i .. " bottles of beer" ) for(i, 99, 1, -1, write( bottles(i), " on the wall, ", bottles(i), ",\n", "take one down, pass it around,\n", bottles(i - 1), " on the wall...
Give a code snippet in #Intercal Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall ...
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#PL.2FI
PL/I
*process source xref attributes or(!); triang: Proc Options(Main); Dcl nn(18,18) Bin Fixed(31); Dcl (rows,i,j) Bin Fixed(31); Dcl (p,k,kn) Bin Fixed(31); Call f_r(1 ,' 55 '); Call f_r(2 ,' 94 48 '); Call f_r(3 ,' ...
Give a code snippet in #PL.2FI Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Go
Go
package main   import ( "bytes" "encoding/csv" "fmt" "html/template" "strings" )   var c = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians...
Give a code snippet in #Go Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Creat...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Picat
Picat
interactive => print("> "), MaxNum = read_int(), Map = new_map(), print("> "), while (Line = read_line(), Line != "") [N,V] = split(Line), Map.put(N.to_int,V), print("> ") end, general_fizzbuzz(MaxNum,Map.to_list.sort), nl.   general_fizzbuzz(N,L) => FB = [I.to_string : I in 1.....
Give a code snippet in #Picat Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along wit...
christopher/rosetta-code
http://rosettacode.org/wiki/List_rooted_trees
List rooted trees
You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all...
#11l
11l
F bagchain(x, n, bb, start = 0) I n == 0 R [x]   [(Int, String)] out L(i) start .< bb.len V (c, s) = bb[i] I c <= n out.extend(bagchain((x[0] + c, x[1]‘’s), n - c, bb, i))   R out   F bags(n) I n == 0 R [(0, ‘’)]   [(Int, String)] upto L(x) (n - 1 .< 0).step(-1) ...
Give a code snippet in #11l You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Perl
Perl
sub ltrim { shift =~ s/^\s+//r } sub rtrim { shift =~ s/\s+$//r } sub trim { ltrim rtrim shift }   # Usage: my $p = " this is a string "; print "'", $p, "'\n"; print "'", trim($p), "'\n"; print "'", ltrim($p), "'\n"; print "'", rtrim($p), "'\n";
Give a code snippet in #Perl Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#PowerShell
PowerShell
  function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j...
Give a code snippet in #PowerShell Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for bei...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
Give a code snippet in #Mathematica.2FWolfram_Language Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Macro If2(condition1, condition2) #Define Else1 ElseIf CBool(condition1) Then #Define Else2 ElseIf CBool(condition2) Then If CBool(condition1) AndAlso CBool(condition2) Then #Endmacro   Sub test(a As Integer, b As Integer) If2(a > 0, b > 0) print "both positive" Else1 print "first posit...
Give a code snippet in #FreeBASIC Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#C.23
C#
public sealed class Singleton1 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: Yes { private static Singleton1 instance; private static readonly object lockObj = new object();   public static Singleton1 Instance { get { lock(lockObj) { if (instance == null) { ...
Give a code snippet in #C.23 A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
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...
#C
C
  #include <stdint.h> /* intptr_t */ #include <stdio.h> #include <stdlib.h> /* bsearch */ #include <string.h> #include <search.h> /* lfind */   #define LEN(x) (sizeof(x) / sizeof(x[0]))   struct cd { char *name; double population; };   /* Return -1 if name could not be found */ int search_get_index_by_name(cons...
Give a code snippet in #C 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]...
christopher/rosetta-code