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/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#Nim
Nim
var msgs: Channel[string] var count: Channel[int]   const FILE = "input.txt"   proc read() {.thread.} = for line in FILE.lines: msgs.send(line) msgs.send("") echo count.recv() count.close()   proc print() {.thread.} = var n = 0 while true: var msg = msgs.recv() if msg.len == 0: break e...
Give a code snippet in #Nim The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#BASIC
BASIC
10 LET A=1.3 20 LET B%=1.3: REM The sigil indicates an integer, so this will be rounded down 30 LET C$="0121": REM The sigil indicates a string data type. the leading zero is not truncated 40 DIM D(10): REM Create an array of 10 digits 50 DIM E$(5.10): REM Create an array of 5 strings, with a maximu...
Give a code snippet in #BASIC Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#8th
8th
  \ ======================================================================================== \ You are given a collection of ABC blocks \ There are twenty blocks with two letters on each block. \ A complete alphabet is guaranteed amongst all sides of the blocks. \ \ Write a function that takes a string (word) and dete...
Give a code snippet in #8th ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#NewLISP
NewLISP
; This is a comment
Give a code snippet in #NewLISP Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
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...
#zkl
zkl
N:=0d1_000_001;   fcn lookAndJustSaying(seed){ // numeric String --> numeric String "9876543210".pump(String,'wrap(n){ (s:=seed.inCommon(n)) and String(s.len(),n) or "" }); } fcn sequence(seed){ // numeric string --> sequence until it repeats seq:=L(); while(not seq.holds(seed)){ seq.append(seed); see...
Give a code snippet in #zkl There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Wren
Wren
//func.call() /* invalid, can't call func before its declared */   var func = Fn.new { System.print("func has been called.") }   func.call() // fine   //C.init() /* not OK, as C is null at this point */   class C { static init() { method() } // fine even though 'method' not yet declared static method() { Syst...
Give a code snippet in #Wren Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Babel
Babel
main: { (1 2 (3 4) 5 6) dup mu disp dup nva disp dup npt disp dup nlf disp dup nin disp dup nhref disp dup nhword disp }   disp! : { %d cr << }  
Give a code snippet in #Babel Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or ...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"WINLIB5" ON ERROR SYS "MessageBox", @hwnd%, REPORT$, 0, 0 : QUIT   REM!WC Windows constants: TVI_SORT = -65533 TVIF_TEXT = 1 TVM_INSERTITEM = 4352 TVS_HASBUTTONS = 1 TVS_HASLINES = 2 TVS_LINESATROOT = 4   REM. TV_INSERTSTRUCT DIM tvi{hPare...
Give a code snippet in #BBC_BASIC A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   h...
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...
#Factor
Factor
USING: formatting fry grouping.extras kernel literals math math.parser math.primes sequences ; IN: rosetta-code.truncatable-primes   CONSTANT: primes $[ 1,000,000 primes-upto reverse ]   : number>digits ( n -- B{} ) number>string string>digits ;   : no-zeros? ( seq -- ? ) [ zero? not ] all? ;   : all-prime? ( seq -- ? ...
Give a code snippet in #Factor 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/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) ...
#ActionScript
ActionScript
for (var i:int = 1; i <= 100; i++) { if (i % 15 == 0) trace('FizzBuzz'); else if (i % 5 == 0) trace('Buzz'); else if (i % 3 == 0) trace('Fizz'); else trace(i); }
Give a code snippet in #ActionScript 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   F...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Phix
Phix
-- -- demo\rosetta\Colour_pinstripe.exw -- ================================= -- with javascript_semantics -- but not yet CD_PRINTER include pGUI.e constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE} --constant colours = {CD_BLACK, CD_WHITE} procedure draw_to(cdCanvas cdcanvas) ...
Give a code snippet in #Phix The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   mage...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#jq
jq
def div(x;y): if y==0 then error("NaN") else x/y end;
Give a code snippet in #jq Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Free_Pascal
Free Pascal
program HelloWorldServer; {$mode objfpc}{$H+} uses Classes, fphttpserver;   Type TTestHTTPServer = Class(TFPHTTPServer) public procedure HandleRequest(Var ARequest: TFPHTTPConnectionRequest; Var AResponse : TFPHTTPConnectionResponse); override; end;   Var Serv : TTestHTTPServer...
Give a code snippet in #Free_Pascal The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested....
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...
#Wren
Wren
/* safe_addition.wren */ class Interval { construct new(lower, upper) { if (lower.type != Num || upper.type != Num) { Fiber.abort("Arguments must be numbers.") } _lower = lower _upper = upper }   lower { _lower } upper { _upper }   static stepAway(x) { new...
Give a code snippet in #Wren 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. Additional...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Raku
Raku
sub propdivsum (\x) { my @l = 1 if x > 1; (2 .. x.sqrt.floor).map: -> \d { unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d } } sum @l }   say bag (1..20000).map: { propdivsum($_) <=> $_ }
Give a code snippet in #Raku These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient ...
christopher/rosetta-code
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub linear_combination { my(@coef) = @$_; my $e = ''; for my $c (1..+@coef) { $e .= "$coef[$c-1]*e($c) + " if $coef[$c-1] } $e =~ s/ \+ $//; $e =~ s/1\*//g; $e =~ s/\+ -/- /g; $e or 0; }   say linear_combination($_) for [1, 2, 3], [0, 1, 2, 3]...
Give a code snippet in #Perl Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , c...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Lua
Lua
socket = require "socket" host, port = "127.0.0.1", 256   sid = socket.udp() sid:sendto( "hello socket world", host, port ) sid:close()
Give a code snippet in #Lua For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => {   // consolidated :: [(Float, Float)] -> [(Float, Float)] const consolidated = xs => foldl((abetc, xy) => 0 < abetc.length ? (() => { const etc = abetc.slice(1), ...
Give a code snippet in #JavaScript Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one ...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Java
Java
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;   public class Digester {   public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); }   static String hexDigest(String str, String diges...
Give a code snippet in #Java Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the W...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Liberty_BASIC
Liberty BASIC
' show where we are print DefaultDir$   ' in here kill "input.txt" result=rmdir("Docs")   ' from root kill "\input.txt" result=rmdir("\Docs")  
Give a code snippet in #Liberty_BASIC Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
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)
#ooRexx
ooRexx
  ::routine isLeapYear use arg year d = .datetime~new(year, 1, 1) return d~isLeapYear  
Give a code snippet in #ooRexx 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/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Io
Io
Give a code snippet in #Io Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Quackery
Quackery
11 times [ i echo sp ]
Give a code snippet in #Quackery Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Inc...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Clojure
Clojure
(defn quot-rem [m n] [(quot m n) (rem m n)])   ; The following prints 3 2. (let [[q r] (quot-rem 11 3)] (println q) (println r))
Give a code snippet in #Clojure Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Raku
Raku
sub Y (&f) { sub (&x) { x(&x) }( sub (&y) { f(sub ($x) { y(&y)($x) }) } ) } sub fac (&f) { sub ($n) { $n < 2 ?? 1 !! $n * f($n - 1) } } sub fib (&f) { sub ($n) { $n < 2 ?? $n !! f($n - 1) + f($n - 2) } } say map Y($_), ^10 for &fac, &fib;
Give a code snippet in #Raku In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to ...
#Arturo
Arturo
n: new 1 d: new 1 calkinWilf: function [] .export:[n,d] [ n: (d - n) + 2 * (n/d) * d tmp: d d: n n: tmp return @[n d] ]   first20: [[1 1]] ++ map 1..19 => calkinWilf print "The first 20 terms of the Calkwin-Wilf sequence are:" print map first20 'f -> ~"|f\0|/|f\1|"   n: new 1 d: new 1 indx: new 1  ...
Give a code snippet in #Arturo The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floati...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT LOOP year=1900,2100 LOOP month="1'3'5'7'8'10'12" SET dayofweek=DATE (number,1,month,year,nummer) IF (dayofweek==5) PRINT year,"-",month ENDLOOP ENDLOOP  
Give a code snippet in #TUSCRIPT The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (t...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#ERRE
ERRE
DIM A%[10] ! the array size is 10 integers   DIM B[10]  ! the array will hold 10 floating point values   DIM C$[12] ! a character array of 12 bytes
Give a code snippet in #ERRE Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#360_Assembly
360 Assembly
  * Find the lowest positive integer whose square ends in 269696 * The logic of the assembler program is simple : * loop for i=524 step 2 * if (i*i modulo 1000000)=269696 then leave loop * next i * output 'Solution is: i=' i ' (i*i=' i*i ')' BABBAGE CSECT ...
Give a code snippet in #360_Assembly Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electron...
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 ...
#Prolog
Prolog
    :- system:set_prolog_flag(double_quotes,codes) .   count_jewels(STONEs0,JEWELs0,COUNT) :- findall(X,(member(X,JEWELs0),member(X,STONEs0)),ALLs) , length(ALLs,COUNT) .    
Give a code snippet in #Prolog 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 cas...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#OCaml
OCaml
let () = let ic = open_in Sys.argv.(1) in let base = int_of_char 'a' in let arr = Array.make 26 0 in try while true do let c = Char.lowercase(input_char ic) in let ndx = int_of_char c - base in if ndx < 26 && ndx >= 0 then arr.(ndx) <- succ arr.(ndx) done with End_of_file -> close_in i...
Give a code snippet in #OCaml Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (ass...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics;   namespace NamesOfGod { public class RowSummer { const int N = 100000; public BigInteger[] p;   private void calc(int n) /* Translated from C */ { p[n] = 0;   ...
Give a code snippet in #C.23 This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has ...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#AutoHotkey
AutoHotkey
msgbox % Clipboard := I(6) return   I(n){ r := "--`n" , s := " " loop % n { k := A_index , r .= "| " loop % n r .= A_index=k ? "1, " : "0, " r := RTrim(r, " ,") , r .= " |`n" } loop % 4*n s .= " " return Rtrim(r,"`n") "`n" s "--" }
Give a code snippet in #AutoHotkey Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION replaceText RETURNS LOGICAL ( i_cfile_list AS CHAR, i_cfrom AS CHAR, i_cto AS CHAR ):   DEF VAR ii AS INT. DEF VAR lcfile AS LONGCHAR.   DO ii = 1 TO NUM-ENTRIES( i_cfile_list ): COPY-LOB FROM FILE ENTRY( ii, i_cfile_list ) TO lcfile. lcfile = REPLACE( lcfile...
Give a code snippet in #OpenEdge.2FProgress Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#Batch_File
Batch File
::Long Multiplication Task from Rosetta Code ::Batch File Implementation   @echo off call :longmul 18446744073709551616 18446744073709551616 answer echo(%answer% exit /b 0 rem The Hellish Procedure rem Syntax: call :longmul <n1> <n2> <variable to store product> :longmul setlocal enabledelayedexpansion rem Def...
Give a code snippet in #Batch_File Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   2...
christopher/rosetta-code
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Icon_and_Unicon
Icon and Unicon
global mlck, nCons, cons   procedure main() mlck := mutex() nCons := 0 cons := mutex(set()) while f := open(":12321","na") do { handle_client(f) critical mlck: if nCons <= 0 then close(f) } end   procedure handle_client(f) critical mlck: nCons +:= 1 thread { selec...
Give a code snippet in #Icon_and_Unicon Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification m...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Perl
Perl
use Algorithm::Combinatorics "subsets"; my @S = ("a","b","c"); my @PS; my $iter = subsets(\@S); while (my $p = $iter->next) { push @PS, "[@$p]" } say join(" ",@PS);
Give a code snippet in #Perl A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given ...
christopher/rosetta-code
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Common_Lisp
Common Lisp
(defstruct alternation (alternatives nil :type list))   (defun alternatives-end-positions (string start) (assert (char= (char string start) #\{)) (loop with level = 0 with end-positions with escapep and commap for index from start below (length string) for c = (char string index) ...
Give a code snippet in #Common_Lisp Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_vide...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#VB-DOS
VB-DOS
  OPTION EXPLICIT   ' Months DATA "January", "February", "March", "April", "May", "June", "July" DATA "August", "September", "October", "November", "December"   ' Days of week DATA "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"   ' Var DIM dDate AS DOUBLE, sMonth(1 TO 12) AS STRING, sDay(1...
Give a code snippet in #VB-DOS This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#JavaScript
JavaScript
<!DOCTYPE html><html lang="en">   <head> <meta charset="UTF-8"> <meta name="keywords" content="Game 21"> <meta name="description" content=" 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose...
Give a code snippet in #JavaScript 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#M4
M4
define(`forever', `ifelse($#,0,``$0'', `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',eval($2+$3),$3,`$4')')')dnl forever(`y',0,1, `eval(y,8) ')
Give a code snippet in #M4 Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. R...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "getf.s7i";   const proc: main is func local var string: fileName is ""; var string: content is ""; begin for fileName range [] ("a.txt", "b.txt", "c.txt") do content := getf(fileName); content := replace(content, "Goodbye London!", "Hello New York!"); ...
Give a code snippet in #Seed7 Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#C
C
/* * Program seconds2string, C89 version. * * Read input from argv[1] or stdin, write output to stdout. */   #define _CRT_SECURE_NO_WARNINGS /* unlocks printf in Microsoft Visual Studio */   #include <stdio.h> #include <stdlib.h>   /* * Converting the number of seconds in a human-readable string. * It is worth no...
Give a code snippet in #C Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#SAS
SAS
/* Initialize an array with integers 1 to 10, and print their sum */ data _null_; array a a1-a10; n=1; do over a; a=n; n=n+1; end; s=sum(of a{*}); put s; run;
Give a code snippet in #SAS Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/D...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Go
Go
package main   import "regexp"   var r = regexp.MustCompile(`^[A-Z]{2}[A-Z0-9]{9}\d$`)   var inc = [2][10]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}, }   func ValidISIN(n string) bool { if !r.MatchString(n) { return false } var sum, p int for i := 10; i >= 0; i-- { p = 1 - p if d :=...
Give a code snippet in #Go An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Java
Java
import java.util.concurrent.CountDownLatch;   public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { ...
Give a code snippet in #Java 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/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { x := big.NewInt(2) x = x.Exp(big.NewInt(3), x, nil) x = x.Exp(big.NewInt(4), x, nil) x = x.Exp(big.NewInt(5), x, nil) str := x.String() fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n", len(str), str[:20], str[len(str)-20:], ) }
Give a code snippet in #Go Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
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) ...
#Groovy
Groovy
1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i }
Give a code snippet in #Groovy 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   FizzBuz...
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) ...
#LabVIEW
LabVIEW
  1. direct:   {S.map {lambda {:i} {if {= {% :i 15} 0} then fizzbuzz else {if {= {% :i 3} 0} then fizz else {if {= {% :i 5} 0} then buzz else :i}}}} {S.serie 1 100}} -> 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz 31...
Give a code snippet in #LabVIEW 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   FizzBu...
christopher/rosetta-code
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , whic...
#Go
Go
package main   import ( "fmt" "strings" )   func lcs(x, y string) string { xl, yl := len(x), len(y) if xl == 0 || yl == 0 { return "" } x1, y1 := x[:xl-1], y[:yl-1] if x[xl-1] == y[yl-1] { return fmt.Sprintf("%s%c", lcs(x1, y1), x[xl-1]) } x2, y2 := lcs(x, y1), lcs(x1...
Give a code snippet in #Go The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Oberon-2
Oberon-2
  (* this is a comment *) (* and this is a multiline comment (* with a nested comment *) *)  
Give a code snippet in #Oberon-2 Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#Erlang
Erlang
: factorial ( n -- n! ) [1,b] product ;   CONSTANT: 10-factorial $[ 10 factorial ]
Give a code snippet in #Erlang Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Lasso
Lasso
define file_truncate(path::string, size::integer) => {   local(file = file(#path))   fail_if(not(#file -> exists), -1, 'There is no file at the given path') fail_if(#file -> size < #size, -1, 'No point in truncating a file to a larger size than it already is')   #file -> setSize(#size)   } local(filepath = '//Libra...
Give a code snippet in #Lasso Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creatin...
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 ...
#ACL2
ACL2
(defun split (xys) (if (endp (rest xys)) (mv xys nil) (mv-let (xs ys) (split (rest (rest xys))) (mv (cons (first xys) xs) (cons (second xys) ys)))))   (defun mrg (xs ys) (declare (xargs :measure (+ (len xs) (len ys)))) (cond ((endp xs) ys) ((endp ys...
Give a code snippet in #ACL2 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/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 ...
#TI-83_BASIC
TI-83 BASIC
  :For(A,2008,2121 :If dayofWk(A,12,25)=1 :Disp A :End  
Give a code snippet in #TI-83_BASIC 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 be...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#VBA
VBA
Private Function Cusip_Check_Digit(s As Variant) As Integer Dim Sum As Integer, c As String, v As Integer For i = 1 To 8 c = Mid(s, i, 1) If IsNumeric(c) Then v = Val(c) Else Select Case c Case "a" To "z" v = Asc(c) - Asc("a") +...
Give a code snippet in #VBA This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric c...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPrime(n As Integer) As Boolean If n < 2 Then Return False If n = 2 Then Return True If n Mod 2 = 0 Then Return False Dim limit As Integer = Sqr(n) For i As Integer = 3 To limit Step 2 If n Mod i = 0 Then Return False Next Return True End Function   ' To test this works,...
Give a code snippet in #FreeBASIC Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other l...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Nim
Nim
import math, strformat, sugar   const N = 1_000_000   #################################################################################################### # Erathostenes sieve.   var composite: array[2..N, bool] # Initialized to false i.e. prime.   for n in 2..int(sqrt(float(N))): if not composite[n]: for k in...
Give a code snippet in #Nim Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes...
christopher/rosetta-code
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cyli...
#Julia
Julia
const cyl = zeros(Bool, 6)   function load() while cyl[1] cyl .= circshift(cyl, 1) end cyl[1] = true cyl .= circshift(cyl, 1) end   spin() = (cyl .= circshift(cyl, rand(1:6)))   fire() = (shot = cyl[1]; cyl .= circshift(cyl, 1); shot)   function LSLSFSF() cyl .= 0 load(); spin(); load();...
Give a code snippet in #Julia The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet...
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.
#Factor
Factor
{ 1 2 3 4 } [ sq . ] each
Give a code snippet in #Factor Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Perl
Perl
use strict; use warnings; use List::Util 'sum';   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   my ($index, $last, $gap, $count) = (0, 0, 0, 0); my $threshold = 10_000_000;   print "Gap Index of gap Starting Niven\n"; while (1) { $count++; next unless 0 == $count % sum split //, $c...
Give a code snippet in #Perl Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. T...
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 ...
#PowerBASIC
PowerBASIC
STDERR "Goodbye, World!"
Give a code snippet in #PowerBASIC 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...
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 ...
#SSEM
SSEM
01000000000000100000000000000000 0. -2 to c 00100000000000000000000000000000 1. 4 to CI 01111111111111111111111111111111 2. -2 00000000000001110000000000000000 3. Stop 11100000000000000000000000000000 4. 7
Give a code snippet in #SSEM 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 f...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Dart
Dart
import 'dart:math' as Math;   num RungeKutta4(Function f, num t, num y, num dt){ num k1 = dt * f(t,y); num k2 = dt * f(t+0.5*dt, y + 0.5*k1); num k3 = dt * f(t+0.5*dt, y + 0.5*k2); num k4 = dt * f(t + dt, y + k3); return y + (1/6) * (k1 + 2*k2 + 2*k3 + k4); }   void main(){ num t = 0; num dt = 0.1; num...
Give a code snippet in #Dart Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equ...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Plain_English
Plain English
An element is a thing with a number.
Give a code snippet in #Plain_English Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative a...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#zkl
zkl
var zero=" \u0398 ",one="\u2219", five=String("\u2500"*4,"\n"), fill=" \n"; var ds=T(" "," \u2219 "," \u2219\u2219 ","\u2219\u2219\u2219 ","\u2219\u2219\u2219\u2219"); fcn mayan(m){ //--> lists of lists of strings (each line of tile) m.toString(20).pump(List,fcn(m){ // 4,005 --> "a05" bars,dots := m....
Give a code snippet in #zkl Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Bracmat
Bracmat
( ( move = n from to via .  !arg:(?n,?from,?to,?via) & (  !n:>0 & move$(!n+-1,!from,!via,!to) & out$("Move disk from pole " !from " to pole " !to) & move$(!n+-1,!via,!to,!from) | ) ) & move$(4,1,2,3) );
Give a code snippet in #Bracmat Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#Raku
Raku
my @states = < Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri Montana Nebraska Nevada New_Hampshire New_Jersey New_Mexico New_Yo...
Give a code snippet in #Raku Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#360_Assembly
360 Assembly
* Largest number divisible by its digits - base10 - 05/05/2020 LANUDIDO CSECT USING LANUDIDO,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) l...
Give a code snippet in #360_Assembly Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero) ...
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
#PL.2FI
PL/I
Declare x bit(1); x='1'b; /* True */ x='0'b; /* False */
Give a code snippet in #PL.2FI 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/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#ALGOL_68
ALGOL 68
  BEGIN STRING printer name = "/dev/lp0"; FILE line printer; IF open (line printer, printer name, stand out channel) = 0 THEN put (line printer, ("Hello world", newline)); close (line printer) ELSE put (stand error, ("Can't contact line printer on ", printer name, newline)); put (sta...
Give a code snippet in #ALGOL_68 Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With s...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Tcl
Tcl
package require Tcl 8.5   # Algorithm from http://introcs.cs.princeton.edu/java/78crypto/ModExp.java.html # but Tcl has arbitrary-width integers and an exponentiation operator, which # helps simplify the code. proc tcl::mathfunc::modexp {a b n} { if {$b == 0} {return 1} set c [expr {modexp($a, $b / 2, $n)**2 % ...
Give a code snippet in #Tcl Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#C.2B.2B
C++
#include <iostream> #include <string> using namespace std;   int main() { string story, input;   //Loop while(true) { //Get a line from the user getline(cin, input);   //If it's blank, break this loop if(input == "\r") break;   //Add the line to the story story += input; }   //...
Give a code snippet in #C.2B.2B This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#SNOBOL4
SNOBOL4
&code = condition errlevel :s(end)
Give a code snippet in #SNOBOL4 Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalize...
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 ...
#Visual_Basic
Visual Basic
If condition Then statement End If   If condition Then statement Else statement End If   If condition1 Then statement ElseIf condition2 Then statement ... ElseIf conditionN Then statement Else statement End If
Give a code snippet in #Visual_Basic 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Racket
Racket
#lang racket ; if we `for` over the port, we won't have the program in memory for 'Q' (define (parse-HQ9+ the-program) (define oTW " on the wall") (and ; ensures the accumulator is never seen! (for/fold ((A 0)) ((token (in-string the-program))) (case token ((#\H) (display "hello, world") A) ...
Give a code snippet in #Racket Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in th...
#Picat
Picat
  main => N = 98, PD = new_array(N*N), % PD[I] = no. of product decompositions of I foreach(I in 1..N*N) PD[I] = 0 end, foreach(X in 2..N-1, Y in X+1..N) PD[X * Y] := PD[X * Y] + 1 end,    % Fact 1: S says "P does not know X and Y.", i.e.  % For every possible sum decomposition of the number X+...
Give a code snippet in #Picat Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Oforth
Oforth
: testQueue | q i | Queue new ->q 20 loop: i [ i q push ] while ( q empty not ) [ q pop . ] ;
Give a code snippet in #Oforth Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#Lua
Lua
import bitops, sequtils, strutils   type Square = seq[seq[int]]   func magicSquareDoublyEven(n: int): Square = ## Build a magic square of doubly even order.   assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4." result = newSeqWith(n, newSeq[int](n))   const bits = 0b1001_0110_0110_1001 #...
Give a code snippet in #Lua A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size th...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#Go
Go
package main   import ( "fmt" "log" )   func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n)   for i := 0; i < n; i++ { result[i...
Give a code snippet in #Go A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a mu...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Factor
Factor
1234567 2 36 [a,b] [ >base print ] with each
Give a code snippet in #Factor Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard ro...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#Julia
Julia
for i in 32:127 c= i== 0 ? "NUL" : i== 7 ? "BEL" : i== 8 ? "BKS" : i== 9 ? "TAB" : i==10 ? "LF " : i==13 ? "CR " : i==27 ? "ESC" : i==155 ? "CSI" : "|$(Char(i))|" print("$(lpad(i,3)) $(string(i,base=16,pad=2)) $c") (i&7)==7 ? println() : print(" ") end
Give a code snippet in #Julia Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#AWK
AWK
  function cmp(i1, v1, i2, v2, u1, u2) { u1 = v1""v2; u2 = v2""v1; return (u2 - u1) } function largest_int_from_concatenated_ints(X) { PROCINFO["sorted_in"]="cmp"; u=""; for (i in X) u=u""X[i]; return u }   BEGIN { split("1 34 3 98 9 76 45 4",X); print largest_int_from_concatenated_ints(X)   split("5...
Give a code snippet in #AWK Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34,...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 ...
#Eiffel
Eiffel
  class PANCAKE_SORT [G -> COMPARABLE]   feature {NONE}   arraymax (array: ARRAY [G]; upper: INTEGER): INTEGER --- Max item of 'array' between index 1 and 'upper'. require upper_index_positive: upper >= 0 array_not_void: array /= Void local i: INTEGER cur_max: G do from i := 1 cur_max ...
Give a code snippet in #Eiffel 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#zkl
zkl
s:="alphaBETA"; s.toLower(); //--> "alphabeta" s.toUpper(); //--> "ALPHABETA"
Give a code snippet in #zkl Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not rev...
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
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(Y,Z) ENTRY TO GCD. A = Y B = Z LOOP WHENEVER A.E.B, FUNCTION RETURN A WHENEVER A.G.B, A = A-B WHENEVER A.L.B, B = B-A TRANSFER TO LOOP END OF FUNCTION   ...
Give a code snippet in #MAD 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/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Retro
Retro
# Strings   This will display the ASCII code for each character in a string   ~~~ 'This_is_a_message [ n:put sp ] s:for-each ~~~   # Array   Display each element   ~~~ { #1 #2 #3 } [ n:put sp ] a:for-each ~~~   # Linked List   Using the dictionary as an example, display each name   ~~~ &Dictionary [ d:name s:put sp ] ...
Give a code snippet in #Retro Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Objeck
Objeck
class Test { function : Main(args : String[]) ~ Nil { Vec2->New(5, 7)->Add(Vec2->New(2, 3))->ToString()->PrintLine(); Vec2->New(5, 7)->Sub(Vec2->New(2, 3))->ToString()->PrintLine(); Vec2->New(5, 7)->Mult(11)->ToString()->PrintLine(); Vec2->New(5, 7)->Div(2)->ToString()->PrintLine(); } }   class Vec2...
Give a code snippet in #Objeck Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Openscad
Openscad
a="straw"; b="berry"; c=str(a,b); /* Concatenate a and b */ echo (c);
Give a code snippet in #Openscad String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string ...
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#Julia
Julia
  msg = "Rosetta Code, Secure temporary file, implemented with Julia."   (fname, tio) = mktemp() println(fname, " created as a temporary file.") println(tio, msg) close(tio) println("\"", msg, "\" written to ", fname)  
Give a code snippet in #Julia Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions...
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations char New(53,40), Old(53,40);   proc Block(X0, Y0, C); \Display a colored block int X0, Y0, C; \big (6x5) coordinates, char int X, Y; [case C of \convert char to color ^H: C:= $9; \blue ^t...
Give a code snippet in #XPL0 Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell t...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#FreeBASIC
FreeBASIC
' version 15-09-2015 ' compile with: fbc -s console   #Define size 31 ' (N * 2 + 1)   Sub pascal_triangle(rows As Integer, Pas_tri() As ULongInt)   Dim As Integer x, y   For x = 1 To rows Pas_tri(1,x) = 1 Pas_tri(x,1) = 1 Next   For x = 2 To rows For y = 2 To rows...
Give a code snippet in #FreeBASIC Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Sidef
Sidef
func x̄(a) { a.sum / a.len }   func σ(a) { sqrt(x̄(a.map{.**2}) - x̄(a)**2) }   const Δ = (%n< -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.19...
Give a code snippet in #Sidef W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Scala
Scala
def ??? = throw new NotImplementedError // placeholder for implementation of hypothetical methods def myFunction0() = ??? myFunction0() // function invoked with empty parameter list myFunction0 // function invoked with empty parameter list omitted   def myFunction = ??? myFunction // function invoked with no...
Give a code snippet in #Scala Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a va...
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
#MACRO-10
MACRO-10
    TITLE HELLO   COMMENT ! Hello-World program, PDP-10 assembly language, written by kjx, 2022. Assembler: MACRO-10 Operating system: TOPS-20 !   SEARCH MONSYM  ;Get symbolic names for system-calls.   GO:: RESET%  ;System call: Initializ...
Give a code snippet in #MACRO-10 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 erro...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  FileByteCount["input.txt"] FileByteCount[FileNameJoin[{$RootDirectory, "input.txt"}]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#PowerShell
PowerShell
function Get-NextAliquot ( [int]$X ) { If ( $X -gt 1 ) { $NextAliquot = 0 (1..($X/2)).Where{ $x % $_ -eq 0 }.ForEach{ $NextAliquot += $_ }.Where{ $_ } return $NextAliquot } }   function Get-AliquotSequence ( [int]$K, [int]$N ) { $X = $K $X (1..($N-1))....
Give a code snippet in #PowerShell An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifica...
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
#MUMPS
MUMPS
a = true b = false   if a println "a is true" else if b println "b is true" end
Give a code snippet in #MUMPS 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/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
#BASIC256
BASIC256
system "dir"
Give a code snippet in #BASIC256 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/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Picat
Picat
go =>  % removing '\n' first Chars = delete_all(read_file_chars("unixdict.txt"),'\n'), M = letter_freq(Chars), println(M.sort_map(values).reverse).   % Get the letter frequency letter_freq(S) = Map => Map = new_map(), foreach(C in S) Map.put(C,Map.get(C,0)+1) end.   % Different sorting function on maps...
Give a code snippet in #Picat Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (ass...
christopher/rosetta-code