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/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Aime
Aime
integer biased(integer bias) { 1 ^ min(drand(bias - 1), 1); }   integer unbiased(integer bias) { integer a;   while ((a = biased(bias)) == biased(bias)) { }   a; }   integer main(void) { integer b, n, cb, cu, i;   n = 10000; b = 3; while (b <= 6) { i = cb = cu = 0; wh...
Give a code snippet in #Aime P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator t...
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....
#Nim
Nim
import strformat   const MAX = 120   proc isPrime(n: int): bool = var d = 5 if n < 2: return false if n mod 2 == 0: return n == 2 if n mod 3 == 0: return n == 3 while d * d <= n: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 return true...
Give a code snippet in #Nim 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 Sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Wren
Wren
/* retrieve_and_search_chat_history.wren */   import "./date" for Date   var CURLOPT_URL = 10002 var CURLOPT_FOLLOWLOCATION = 52 var CURLOPT_WRITEFUNCTION = 20011 var CURLOPT_WRITEDATA = 10001   class C { foreign static searchStr foreign static utcNow // format will be yyyy-mm-dd hh:MM:ss }   foreign class Buff...
Give a code snippet in #Wren Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or ...
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.
#Common_Lisp
Common Lisp
(defun sum-3-5-slow (limit) (loop for x below limit when (or (zerop (rem x 3)) (zerop (rem x 5))) sum x))
Give a code snippet in #Common_Lisp 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/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#J
J
require 'dll' strdup=: 'msvcrt.dll _strdup >x *' cd < free=: 'msvcrt.dll free n x' cd < getstr=: free ] memr@,&0 _1   DupStr=:verb define try. getstr@strdup y catch. y end. )
Give a code snippet in #J Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#AutoHotkey
AutoHotkey
leapyear(year) { if (Mod(year, 100) = 0) return (Mod(year, 400) = 0) return (Mod(year, 4) = 0) }   MsgBox, % leapyear(1604)
Give a code snippet in #AutoHotkey Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π ...
#C
C
#include "gmp.h"   void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); }   int main (void) { mpf_set_default_prec (300000); mpf_t x0, y0, resA, resB, Z, var;   mpf_init_set_ui (x0, 1); mpf_in...
Give a code snippet in #C Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize th...
christopher/rosetta-code
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch...
#Factor
Factor
USING: io kernel lists lists.lazy math.ranges math.text.utils math.vectors prettyprint sequences ;   : disarium? ( n -- ? ) dup 1 digit-groups dup length 1 [a,b] v^ sum = ;   : disarium ( -- list ) 0 lfrom [ disarium? ] lfilter ;   19 disarium ltake [ pprint bl ] leach nl
Give a code snippet in #Factor A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the firs...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Forth
Forth
s" foo.txt" slurp-file ( str len )
Give a code snippet in #Forth Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incre...
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 ...
#360_Assembly
360 Assembly
* Find the missing permutation - 19/10/2015 PERMMISX CSECT USING PERMMISX,R15 set base register LA R4,0 i=0 LA R6,1 step LA R7,23 to LOOPI BXH R4,R6,ELOOPI do i=1 to hbound(perms) LA R5,0 ...
Give a code snippet in #360_Assembly ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Gambas
Gambas
Public Sub Main() Dim sTemp As String   Print "Command to start the program was ";;   For Each sTemp In Args.All Print sTemp;; Next   End
Give a code snippet in #Gambas The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script...
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
#PDP-11_Assembly
PDP-11 Assembly
; Execute a file - the equivalent of system() in stdio ; ; On entry, r1=>nul-terminated command string ; On exit, VS=Couldn't fork ; VC=Forked successfully, r0=return value ; .CLIsystem trap 2 ; fork() br CLIchild ; Child process returns here bcc CLIparent ; Parent process returns here mov (sp)+,r1 t...
Give a code snippet in #PDP-11_Assembly 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/Levenshtein_distance/Alignment
Levenshtein distance/Alignment
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used t...
#Sidef
Sidef
func align(s, t) { s.chars!.prepend!('^') t.chars!.prepend!('^')   var A = [] {|i| A[i][0]{@|<d s t>} = (i, s.ft(1, i).join, '~' * i) } << ^s {|i| A[0][i]{@|<d s t>} = (i, '-' * i, t.ft(1, i).join) } << ^t   for i (1 .. s.end) { for j (1 .. t.end) { if (s[i] != t[j]) { A[...
Give a code snippet in #Sidef The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#Ruby
Ruby
puts "Lowercase:", [*"a".."z"].join, "Uppercase:", [*"A".."Z"].join
Give a code snippet in #Ruby Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task r...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Python
Python
maxprime = 1000000   def primes(n): multiples = set() prime = [] for i in range(2, n+1): if i not in multiples: prime.append(i) multiples.update(set(range(i*i, n+1, i))) return prime   def truncatableprime(n): 'Return a longest left and right truncatable primes below ...
Give a code snippet in #Python A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncata...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#8th
8th
  "http://www.rosettacode.org" net:get drop >s .  
Give a code snippet in #8th Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#WDTE
WDTE
let max a b => a { < b => b };   let ! n => n { > 1 => - n 1 -> ! -> * n } -> max 1;
Give a code snippet in #WDTE Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Vim_Script
Vim Script
" return character under cursor function! CurrChar() return matchstr(getline('.'), '\%' . col('.') . 'c.') endfunction   " draw all-white grid (arguments are characters to use for white and black) function! LangtonClear(white, black) let l:bufname = 'langtons.ant' if bufexists(l:bufname) let l:winnum = bufw...
Give a code snippet in #Vim_Script Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Nim
Nim
type Foo = object a: float b: string c: seq[int] let f = Foo(a: 0.9, b: "hi", c: @[1,2,3]) for n, v in f.fieldPairs: echo n, ": ", v
Give a code snippet in #Nim Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#Java
Java
import java.io.File; import java.util.*;   public class TopRankPerGroup {   private static class Employee { final String name; final String id; final String department; final int salary;   Employee(String[] rec) { name = rec[0]; id = rec[1]; ...
Give a code snippet in #Java Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,S...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#Kotlin
Kotlin
// version 1.2.60   fun isPrime(n: Long): Boolean { if (n % 2L == 0L) return n == 2L if (n % 3L == 0L) return n == 3L var d = 5L while (d * d <= n) { if (n % d == 0L) return false d += 2L if (n % d == 0L) return false d += 4L } return true }   fun main(args: Array...
Give a code snippet in #Kotlin Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which...
christopher/rosetta-code
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
#NewLISP
NewLISP
; file: input-gui.lsp ; url: http://rosettacode.org/wiki/User_input/Graphical ; author: oofoe 2012-02-02   ; Colours (setq ok '(.8 1 .8) fail '(1 .5 .5))   ; Load library and initialize GUI server: (load (append (env "NEWLISPDIR") "/guiserver.lsp")) (gs:init)   ; Validation Callback   ; There is a bug in the "gs...
Give a code snippet in #NewLISP 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/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Erlang
Erlang
-module(population_count). -export([popcount/1]).   -export([task/0]).   popcount(N) -> popcount(N,0).   popcount(0,Acc) -> Acc; popcount(N,Acc) -> popcount(N div 2, Acc + N rem 2).   threes(_,0,Acc) -> lists:reverse(Acc); threes(Threes,N,Acc) -> threes(Threes * 3, N-1, [popcount(Threes)|Acc]).   th...
Give a code snippet in #Erlang Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop coun...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#K
K
lcase  : _ci 97+!26 ucase  : _ci 65+!26 tolower : {@[x;p;:;lcase@n@p:&26>n:ucase?/:x]} panagram: {&/lcase _lin tolower x}
Give a code snippet in #K Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a...
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Common_Lisp
Common Lisp
(defun forward-difference (list) (mapcar #'- (rest list) list))   (defun nth-forward-difference (list n) (setf list (copy-list list)) (loop repeat n do (map-into list #'- (rest list) list)) (subseq list 0 (- (length list) n)))
Give a code snippet in #Common_Lisp Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. ...
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...
#Ela
Ela
open number string math   digit x y z k = [[x],[x,x],[x,x,x],[x,y],[y],[y,x],[y,x,x],[y,x,x,x],[x,z]] : (toInt k - 1)   toRoman 0 = "" toRoman x | x < 0 = fail "Negative roman numeral" | x >= 1000 = 'M' :: toRoman (x - 1000) | x >= 100 = let (q,r) = x `divrem` 100 in ...
Give a code snippet in #Ela 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/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#ATS
ATS
implement main0 () = fprint (stderr_ref, "Goodbye, World!\n")
Give a code snippet in #ATS Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". ...
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ToExpression[Input["function? E.g. Sin",]][Input["value? E.g. 0.4123"]]
Give a code snippet in #Mathematica.2FWolfram_Language 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/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#zonnon
zonnon
  module MatrixOps; type Matrix = array {math} *,* of integer;     procedure WriteMatrix(x: array {math} *,* of integer); var i,j: integer; begin for i := 0 to len(x,0) - 1 do for j := 0 to len(x,1) - 1 do write(x[i,j]); end; writeln; end end WriteMatrix;   procedure Transposition; var m,x:...
Give a code snippet in #zonnon Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#Java
Java
public class SquaresCubes { public static boolean isPerfectCube(long n) { long c = (long)Math.cbrt((double)n); return ((c * c * c) == n); }   public static void main(String... args) { long n = 1; int squareOnlyCount = 0; int squareCubeCount = 0; while ((square...
Give a code snippet in #Java Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Icon_and_Unicon
Icon and Unicon
procedure main() write(0^0) end
Give a code snippet in #Icon_and_Unicon Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or ...
#Phix
Phix
-- demo\rosetta\PythagorasTree.exw with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas enum FILL, BORDER procedure drawTree(atom x1, y1, x2, y2, integer depth, dd) atom dx = x2 - x1, dy = y1 - y2, x3 = x2 - dy, y3 = y2 - dx, x4 = x1 - dy, ...
Give a code snippet in #Phix The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Explore
Explore
> Array.create 6 'A';; val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|] > Array.init 8 (fun i -> i * 10) ;; val it : int [] = [|0; 10; 20; 30; 40; 50; 60; 70|] > let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;; val arr : int [] = [|0; 1; 2; 3; 4; 5; 6|] > arr.[4];; val it : int = 4 > arr.[4] <- 65 ;; val it : unit = () > arr;;...
Give a code snippet in #Explore This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and ret...
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
#IWBASIC
IWBASIC
  OPENCONSOLE   PRINT"Hello world!"   'This line could be left out. PRINT:PRINT:PRINT"Press any key to end."   'Keep the console from closing right away so the text can be read. DO:UNTIL INKEY$<>""   CLOSECONSOLE   END  
Give a code snippet in #IWBASIC 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...
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...
#Phix
Phix
with javascript_semantics string n = "000000" function incn() for i=length(n) to 1 by -1 do if n[i]='9' then if i=1 then return false end if n[i]='0' else n[i] += 1 exit end if end for return true end function sequence res = {}, bes...
Give a code snippet in #Phix 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, 31131...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#OCaml
OCaml
print_string "Hello world!\n";;
Give a code snippet in #OCaml Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#jq
jq
# Example values: # $re : -0.8 # $im : 0.156 {} | range(-100; 101; 10) as $v | (( range (-280; 281; 10) as $h | .x = $h / 200 | .y = $v / 100 | .plot = "#" | .i = 0 | until (.i == 50 or .plot == "."; .i += 1 | .z_real = ((.x * .x) - (.y * .y) + $re) | .z_imag = ((.x * .y * 2) ...
Give a code snippet in #jq Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d ...
#Vlang
Vlang
import math   // vlang doesn't have globals const ( p = [151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149...
Give a code snippet in #Vlang The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random...
christopher/rosetta-code
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table
Display an outline as a nested table
Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. defining the width of a ...
#JavaScript
JavaScript
(() => { "use strict";   // ----------- NESTED TABLES FROM OUTLINE ------------   // wikiTablesFromOutline :: [String] -> String -> String const wikiTablesFromOutline = colorSwatch => outline => forestFromIndentedLines( indentLevelsFromLines(lines(outline)) ) .map(wik...
Give a code snippet in #JavaScript Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to ev...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Wart
Wart
with infile "input.txt" with outfile "output.txt" whilet line (read_line) prn line
Give a code snippet in #Wart File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file in...
christopher/rosetta-code
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#Phix
Phix
with javascript_semantics function throwDie(integer nSides, nDice, s, sequence counts) if nDice == 0 then counts[s] += 1 else for i=1 to nSides do counts = throwDie(nSides, nDice-1, s+i, counts) end for end if return counts end function function beatingProbability(i...
Give a code snippet in #Phix Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def RandomNormal drop rand log -2 * sqrt 2 pi * rand * cos * 0.5 * 1 + enddef   1000 var n 0 n repeat   getid RandomNormal map   dup sum n / var mean "Mean: " print mean print nl   0 swap n for get mean - 2 power rot + swap endfor swap n / sqrt "Standard deviation: " print print
Give a code snippet in #Phixmonti Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Rel...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#min
min
(('' '' '') => spread if) :if?   ((1 0 if?) concat map sum) :count   (swap indexof -1 !=) :member?   (("" split) dip 'member? cons count) :count-jewels   "aAAbbbb" "aA" count-jewels puts! "ZZ" "z" count-jewels puts!
Give a code snippet in #min Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case l...
christopher/rosetta-code
http://rosettacode.org/wiki/Imaginary_base_numbers
Imaginary base numbers
Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.] Other imagi...
#Java
Java
public class ImaginaryBaseNumber { private static class Complex { private Double real, imag;   public Complex(double r, double i) { this.real = r; this.imag = i; }   public Complex(int r, int i) { this.real = (double) r; this.imag = (do...
Give a code snippet in #Java Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science tale...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Crystal
Crystal
arr1 = [1, 2, 3] arr2 = ["foo", "bar", "baz"] arr1 + arr2 #=> [1, 2, 3, "foo", "bar", "baz"]
Give a code snippet in #Crystal Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#ALGOL_W
ALGOL W
begin integer array a ( 1 :: 5 ); integer array b ( 2 :: 4 ); integer array c ( 1 :: 8 );    % concatenates the arrays a and b into c  %  % the lower and upper bounds of each array must be specified in %  % the corresponding *Lb and *Ub parameters  % pr...
Give a code snippet in #ALGOL_W Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/The_sieve_of_Sundaram
The sieve of Sundaram
The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integers, mark every third starting a...
#ALGOL_68
ALGOL 68
BEGIN # sieve of Sundaram # INT n = 8 000 000; INT none = 0, mark1 = 1, mark2 = 2; [ 1 : n ]INT mark; FOR i FROM LWB mark TO UPB mark DO mark[ i ] := none OD; FOR i FROM 4 BY 3 TO UPB mark DO mark[ i ] := mark1 OD;   INT count := 0; # Count of primes. # [ 1 : 100 ]INT ...
Give a code snippet in #ALGOL_68 The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve int...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Forth
Forth
\ Rosetta Code Strip Comment   : LASTCHAR ( addr len -- addr len c) 2DUP + C@ ; : COMMENT? ( char -- ? ) S" #;" ROT SCAN NIP ; \ test char for "#;" : -LEADING ( addr len -- addr' len') BL SKIP ; \ remove leading space characters   : -COMMENT ( addr len -- addr len') \ removes # or ; comments 1-...
Give a code snippet in #Forth Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. W...
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 ...
#PicoLisp
PicoLisp
(mapc println '(a "cde" (X Y Z) 999))
Give a code snippet in #PicoLisp 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: Defi...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT check="1'3'1'7'3'9" values="123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" value=STRINGS (values,":<%:") BUILD r_TABLE/or illegal=":A:E:I:O:U:" LOOP input="710889'B0YBKJ'406566'B0YBLH'228276'B0YBKL'557910'B0YBKR'585284'B0YBKT'BOYAKT'B00030",sum="" IF (input.ma.illegal) THEN PRINT/ERROR input, " illegal" ...
Give a code snippet in #TUSCRIPT Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852...
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...
#Tcl
Tcl
package require Tcl 8.6   oo::class create MoveToFront { variable symbolTable constructor {symbols} { set symbolTable [split $symbols ""] }   method MoveToFront {table index} { list [lindex $table $index] {*}[lreplace $table $index $index] } method encode {text} { set t $symbolTable set r {}...
Give a code snippet in #Tcl 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   static class Module1 { static Random r = new Random();   static List<int> getThree(int n) { List<int> g3 = new List<int>(); for (int i = 0; i < 4; i++) g3.Add(r.Next(n) + 1); g3.Sort(); g3.RemoveAt(0); return g3; ...
Give a code snippet in #C.23 RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sid...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Python
Python
from itertools import permutations import math     def derangements(n): 'All deranged permutations of the integers 0..n-1 inclusive' return ( perm for perm in permutations(range(n)) if all(indx != p for indx, p in enumerate(perm)) )   def subfact(n): if n == 2 or n == 0: return 1 el...
Give a code snippet in #Python A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Golfscript
Golfscript
{*}:multiply;
Give a code snippet in #Golfscript A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to dist...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#Scheme
Scheme
  (import (scheme base) (scheme file) (scheme process-context) (scheme write) (only (srfi 13) string-delete string-index string-trim))   ;; Mappings from operation symbols to internal procedures. ;; We define operations appropriate to virtual machine: ;; e.g. division must return an int,...
Give a code snippet in #Scheme An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer i...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Factor
Factor
USING: io kernel math math.parser math.primes.factors sequences ;   27720 factors [ number>string ] map " " join print ;
Give a code snippet in #Factor The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the...
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 ...
#Arturo
Arturo
sortTable: function [tbl][ column: "0" reversed?: false unless null? c: <= attr 'column -> column: to :string c unless null? attr 'reverse -> reversed?: true   result: new sort.by: column map tbl 'r [ to :dictionary flatten couple 0..dec size r r ]   if reversed? -> reverse 'result  ...
Give a code snippet in #Arturo 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; le...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Arturo
Arturo
middleThree: function [num][ n: to :string abs num if 3 > size n -> return "Number must have at least three digits" if even? size n -> return "Number must have an odd number of digits"   middle: ((size n)/2)- 1 return slice n middle middle+2 ]   samples: @[ 123, 12345, 1234567, 987654321, 1000...
Give a code snippet in #Arturo Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be t...
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.
#HicEst
HicEst
! bound to application CALL F2 ! ... END   SUBROUTINE F2 ! this text shows as tooltip text. F2 ... F9 are possible ! synchronous call: CALL F2 ! asynchronous calls: F2 key ! mouse click on the F2 toolbar tool ! ALARM( delay_seconds, 2 )   ! che...
Give a code snippet in #HicEst 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/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...
#Rust
Rust
// 20210210 Rust programming solution   extern crate chrono; use chrono::prelude::*;   fn main() { let utc: DateTime<Utc> = Utc::now(); println!("{}", utc.format("%d/%m/%Y %T")); }  
Give a code snippet in #Rust 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   D...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Elena
Elena
import extensions;   public program() { for(int i := 0, i < 5, i += 1) { for(int j := 0, j <= i, j += 1) { console.write:"*" };   console.writeLine() } }
Give a code snippet in #Elena “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Nanoquery
Nanoquery
a = "Hello" b = a
Give a code snippet in #Nanoquery This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#UNIX_Shell
UNIX Shell
alist=( item1 item2 item3 ) # creates a 3 item array called "alist" declare -a list2 # declare an empty list called "list2" declare -a list3[0] # empty list called "list3"; the subscript is ignored   # create a 4 item list, with a specific order list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)
Give a code snippet in #UNIX_Shell This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and ...
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 ......
#Liberty_BASIC
Liberty BASIC
ndigits = 0   q = 1 r = 0 t = q k = q n = 3 L = n   first = 666 ' ANY non-zero =='true' in LB.   while ndigits <100 if ( 4 *q +r -t) <( n *t) then print n; ndigits =ndigits +1 if not( ndigits mod 40) th...
Give a code snippet in #Liberty_BASIC 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 deci...
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 ......
#M2000_Interpreter
M2000 Interpreter
  Module Checkpi { Module FindPi(Digits){ Digits++ n=Int(3.32*Digits) PlusOne=Lambda N=0% -> { =N N++ } PlusTwo=Lambda N=1% -> { =N N+=2 } Dim A(n)<<PlusOne(...
Give a code snippet in #M2000_Interpreter 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Modula-3
Modula-3
MODULE Gamma EXPORTS Main;   FROM IO IMPORT Put; FROM Fmt IMPORT Extended, Style;   PROCEDURE Taylor(x: EXTENDED): EXTENDED = CONST a = ARRAY [0..29] OF EXTENDED { 1.00000000000000000000X0, 0.57721566490153286061X0, -0.65587807152025388108X0, -0.04200263503409523553X0, 0.16653861138229148950X0, -0.0421977...
Give a code snippet in #Modula-3 Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#360_Assembly
360 Assembly
* Knapsack problem/0-1 16/02/2017 KNAPSA01 CSECT USING KNAPSA01,R13 B 72(R15) DC 17F'0' STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 end of prolog L R0,N n LA R1,1 POWER MH ...
Give a code snippet in #360_Assembly A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it wi...
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 ...
#Racket
Racket
  (define sublists (match-lambda** [(0 _) '(())] [(_ '()) '()] [(m (cons x xs)) (append (map (curry cons x) (sublists (- m 1) xs)) (sublists m xs))]))   (define (combinations n m) (sublists n (range m)))  
Give a code snippet in #Racket 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Wren
Wren
var a = [0] var used = { 0: true } var used1000 = { 0: true } var foundDup = false var n = 1 while (n <= 15 || !foundDup || used1000.count < 1001) { var next = a[n-1] - n if (next < 1 || used[next]) next = next + 2*n var alreadyUsed = used[next] a.add(next) if (!alreadyUsed) { used[next] = t...
Give a code snippet in #Wren The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 ...
#Lua
Lua
  local Y = function (f) return (function(x) return x(x) end)(function(x) return f(function(...) return x(x)(...) end) end) end   function stoogesort(L, pred)   pred = pred or function(a,b) return a < b end   Y(function(recurse) return function(i,j) if pred(L[j], L[i]) then L[j],L[i] = L[i],L[j]...
Give a code snippet in #Lua 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/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Phix
Phix
-- demo\rosetta\Runtime_evaluation.exw without javascript_semantics requires("1.0.1") include eval.e -- (not an autoinclude, pulls in around 90% of the interpreter/compiler proper) string code = """ integer i = 0 bool r_init = false sequence r if not r_init then r = {} end if for k=1 to 4 do i += k r &= k end...
Give a code snippet in #Phix Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicab...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#ERRE
ERRE
  PROGRAM EVAL   ! ! arithmetic expression evaluator !   !$KEY   LABEL 98,100,110   DIM STACK$[50]   PROCEDURE DISEGNA_STACK  !$RCODE="LOCATE 3,1"  !$RCODE="COLOR 0,7" PRINT(TAB(35);"S T A C K";TAB(79);)  !$RCODE="COLOR 7,0" FOR TT=1 TO 38 DO IF TT>=20 THEN  !$RCODE="LOCATE 3+TT-19,40" ELSE ...
Give a code snippet in #ERRE Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a sim...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Ruby
Ruby
'1234'.succ #=> '1235' '99'.succ #=> '100'
Give a code snippet in #Ruby Task Increment a numerical string.
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...
#PHP
PHP
<?php   $valid = 0; for ($police = 2 ; $police <= 6 ; $police += 2) { for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) { $fire = 12 - $police - $sanitation; if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) { echo 'Police: ', $police, ', S...
Give a code snippet in #PHP 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 (diff...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Cowgol
Cowgol
include "cowgol.coh";   # Only functions that implement an interface can be passed around # The interface is a type and must be defined before it is used # This defines an interface for a function that takes no arguments interface Fn();   # This function repeats a function that implements Fn sub Repeat(f: Fn, n: uint32...
Give a code snippet in #Cowgol Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
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...
#TI-89_BASIC
TI-89 BASIC
■ dim("møøse") 5
Give a code snippet in #TI-89_BASIC 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 graphem...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Logo
Logo
; Determine if a Gregorian calendar year is leap to leap? :year output (and equal? 0 modulo :year 4 not member? modulo :year 400 [100 200 300] ) end   ; Convert Gregorian calendar date to a simple day count from ; day 1 = January 1, 1 CE to day_number :year :month :day local "elapsed make "elapsed dif...
Give a code snippet in #Logo A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#min
min
(dup reverse ==) :palindrome? (dup "" split reverse "" join ==) :str-palindrome?   "apple" str-palindrome? puts "racecar" str-palindrome? puts (a b c) palindrome? puts (a b b a) palindrome? puts
Give a code snippet in #min A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a...
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Common_Lisp
Common Lisp
(defun DegToDeg (a) (rem a 360)) (defun GradToGrad (a) (rem a 400)) (defun MilToMil (a) (rem a 6400)) (defun RadToRad (a) (rem a (* 2 pi)))   (defun DegToGrad (a) (GradToGrad (* (/ a 360) 400))) (defun DegToRad (a) (RadToRad (* (/ a 360) (* 2 pi)))) (defun DegToMil (a) (MilToMil (* (/ a 360) 6400)))   (defun GradToDeg ...
Give a code snippet in #Common_Lisp This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full tur...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Nim
Nim
const TCIFLUSH: cint = 0 proc tcflush(fd, queue_selector: cint): cint {.header: "termios.h".}   discard tcflush(cint(getFileHandle(stdin)), TCIFLUSH)
Give a code snippet in #Nim Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
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...
#Scala
Scala
object TokenizeStringWithEscaping0 extends App {   val (markerSpE,markerSpF) = ("\ufffe" , "\uffff")   def tokenize(str: String, sep: String, esc: String): Array[String] = {   val s0 = str.replace( esc + esc, markerSpE).replace(esc + sep, markerSpF) val s = if (s0.last.toString == esc) s0.replace(esc, "") +...
Give a code snippet in #Scala 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 spli...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#AutoIt
AutoIt
;AutoIt Version: 3.2.10.0 $num = "45 54" consolewrite ("Sum of " & $num & " is: " & sum($num)) Func sum($numbers) $numm = StringSplit($numbers," ") Return $numm[1]+$numm[$numm[0]] EndFunc
Give a code snippet in #AutoIt A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separat...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Forth
Forth
: init ( n -- ) here swap cells erase 1 here ! ; : .line ( n -- ) cr here swap 0 do dup @ . cell+ loop drop ; : next ( n -- ) here swap 1- cells here + do i @ i cell+ +! -1 cells +loop ; : pascal ( n -- ) dup init 1 .line 1 ?do i next i 1+ .line loop ;
Give a code snippet in #Forth Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#Action.21
Action!
INT FUNC Compare(INT ARRAY x INT xLen INT ARRAY y INT yLen) INT i,len   len=xLen IF len>yLen THEN len=yLen FI FOR i=0 TO len-1 DO IF x(i)>y(i) THEN RETURN (1) ELSEIF x(i)<y(i) THEN RETURN (-1) FI OD IF xLen>yLen THEN RETURN (1) ELSEIF xLen<yLen THEN RETURN (-1) FI...
Give a code snippet in #Action.21 sorting 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Jensen_Device is function Sum ( I : not null access Float; Lo, Hi : Float; F : access function return Float ) return Float is Temp : Float := 0.0; begin I.all := Lo; while I.all <= Hi loop ...
Give a code snippet in #Ada Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#Sidef
Sidef
func part(_, {.is_empty}) { [[]] } func partitions({.is_empty}) { [[]] }   func part(s, args) { gather { s.combinations(args[0], { |*c| part(s - c, args.ft(1)).each{|r| take([c] + r) } }) } }   func partitions(args) { part(@(1..args.sum), args) }   [[],[0,0,0],[1,1,1],[2,0,2]].each { |test_case| ...
Give a code snippet in #Sidef In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a ...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#PureBasic
PureBasic
fun fizzbuzz(n :: NumPositive) -> String: doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'. For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.``` ask: | num-modulo(n, 15) == 0 then: "FizzB...
Give a code snippet in #PureBasic Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   Fizz...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Delphi
Delphi
  program Matrix_multiplication;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TMatrix = record values: array of array of Double; Rows, Cols: Integer; constructor Create(Rows, Cols: Integer); class operator Multiply(a: TMatrix; b: TMatrix): TMatrix; function ToString: string; end;   { TM...
Give a code snippet in #Delphi Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
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 ...
#Clojure
Clojure
(defn combinations "If m=1, generate a nested list of numbers [0,n) If m>1, for each x in [0,n), and for each list in the recursion on [x+1,n), cons the two" [m n] (letfn [(comb-aux [m start] (if (= 1 m) (for [x (range start n)] (list x)) (for [x (range start n) xs (comb-aux (d...
Give a code snippet in #Clojure 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...
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 ...
#AutoHotkey
AutoHotkey
Gosub start ; create and show the gui sort_table("Text", column := 2, reverse := 1) ; lexicographic sort Sleep, 2000 sort_table("Integer", column := 2, reverse := 1) ; numerical sort Return   start: Gui, Add, ListView, r20 w200, 1|2|3 data = ( 1,2,3 b,q,z c,z,z ) Loop, Parse, data, `n { String...
Give a code snippet in #AutoHotkey 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#C
C
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h>   bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) retu...
Give a code snippet in #C Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#Java
Java
import java.awt.*; import java.awt.event.*; import javax.swing.*;   public class Honeycombs extends JFrame {   public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new Honeycombs(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setV...
Give a code snippet in #Java The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two an...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#VBScript
VBScript
iexpmax = 15 n=1 out="" For iexp = 2 To iexpmax If iexp = 2 Then s = 0 Else s = 4 End If n = (n + 1) * 2 - 1 For i = 1 To iexp - 2 s = (s * s - 2) Mod n Next If s = 0 Then out=out & "M" & iexp & " " End If Next Wscript.echo out
Give a code snippet in #VBScript Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Lang5
Lang5
swap # stack reverse # array
Give a code snippet in #Lang5 Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericit...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#MMIX
MMIX
sep IS ',' EOS IS 0 NL IS 10 // main registers p IS $255 tp GREG c GREG t GREG   LOC Data_Segment GREG @ Text BYTE "Hello,How,Are,You,Today",EOS token BYTE 0 eot IS @+255   LOC #100 % main () { Main LDA p,Text % LDA tp,token % initialize pointers 2H LDBU c,p % DO get char BZ c,5F % break if char == EOS CMP ...
Give a code snippet in #MMIX Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rel...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#IDL
IDL
print,total(array^2)
Give a code snippet in #IDL Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
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
#PDP-1_Assembly
PDP-1 Assembly
  hello / above: title line - was punched in human readable letters on paper tape / below: location specifier - told assembler what address to assemble to 100/ lup, lac i ptr / load ac from address stored in pointer cli / clear io register lu2, rcl 6s / rotate combined ac + io reg 6 bits to the left / left...
Give a code snippet in #PDP-1_Assembly 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/Standar...
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...
#ProDOS
ProDOS
enableextensions enabledelayedexpansion editvar /newvar /value=0 /title=closed editvar /newvar /value=1 /title=open editvar /newvar /range=1-100 /increment=1 /from=2 editvar /newvar /value=2 /title=next :doors for /alloccurrences (!next!-!102!) do editvar /modify /value=-open- editvar /modify /value=-next-=+1 if -next...
Give a code snippet in #ProDOS 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/Abelian_sandpile_model/Identity
Abelian sandpile model/Identity
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addition on sandpiles is done by a...
#OCaml
OCaml
    (* https://en.wikipedia.org/wiki/Abelian_sandpile_model *)   module Make = functor (M : sig val m : int val n : int end) -> struct   type t = { grid : int array array ; unstable : ((int*int),unit) Hashtbl.t }   let make () = { grid = Array.init M.m (fun _ -> Array.make M.n 0); unstable = Hashtbl.create ...
Give a code snippet in #OCaml Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Add...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#BASIC256
BASIC256
print "enter a number, n = "; input n print string(n) + "! = " + string(factorial(n))   function factorial(n) factorial = 1 if n > 0 then for p = 1 to n factorial *= p next p end if end function
Give a code snippet in #BASIC256 Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of ...
christopher/rosetta-code