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/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of...
#Perl
Perl
use strict; use warnings; use feature 'say';   package MRG32k3a {   use constant { m1 => 2**32 - 209, m2 => 2**32 - 22853 };   use Const::Fast; const my @a1 => < 0 1403580 -810728>; const my @a2 => <527612 0 -1370589>;   sub new { my ($class,undef,$seed) = @_; ...
Give a code snippet in #Perl MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /...
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)
#C.2B.2B
C++
g++ -std=c++11 leap_year.cpp
Give a code snippet in #C.2B.2B 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/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Tcl
Tcl
# Create one element at a time: set hash(foo) 5   # Create in bulk: array set hash { foo 5 bar 10 baz 15 }   # Access one element: set value $hash(foo)   # Output all values: foreach key [array names hash] { puts $hash($key) }
Give a code snippet in #Tcl Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, El...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Perl
Perl
$ perl -de1   Loading DB routines from perl5db.pl version 1.3 Editor support available.   Enter h or `h h' for help, or `man perldebug' for more help.   main::(-e:1): 1 DB<1> sub f {my ($s1, $s2, $sep) = @_; $s1 . $sep . $sep . $s2}   DB<2> p f('Rosetta', 'Code', ':') Rosetta::Code DB<3> q
Give a code snippet in #Perl Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
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.)
#Scilab
Scilab
// this is a comment i=i+1 // this is a comment
Give a code snippet in #Scilab 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/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#C.23
C#
int a = 0;   do { a += 1; Console.WriteLine(a); } while (a % 6 != 0);
Give a code snippet in #C.23 Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Do...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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) Task Write a function to compute the arithmetic-geomet...
#XPL0
XPL0
include c:\cxpl\codesi; real A, A1, G; [Format(0, 16); A:= 1.0; G:= 1.0/sqrt(2.0); repeat A1:= (A+G)/2.0; G:= sqrt(A*G); A:= A1; RlOut(0, A); RlOut(0, G); RlOut(0, A-G); CrLf(0); until A=G; ]
Give a code snippet in #XPL0 This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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) Task Write a function to...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#PicoLisp
PicoLisp
(make (in '(host "www.kame.net") (while (from "address ") (link (till "^J" T)) ) ) )
Give a code snippet in #PicoLisp DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. 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 l...
#Erlang
Erlang
  -module (main). -export ([main/0]).   main() -> io:fwrite( "SPAM~n" ), main().  
Give a code snippet in #Erlang Task Print out       SPAM       followed by a   newline   in an infinite loop. 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   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const array float: numbers is [] (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);   const func proc: main is func local var float: number is 0.0; var float: sum is 0.0; var float: product is 1.0; var float: reciprocalSum is 0.0; begin for nu...
Give a code snippet in #Seed7 Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldo...
christopher/rosetta-code
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Racket
Racket
#lang racket   (require racket/dict)   ;; G is a dictionary of vertex -> (list vertex) (define (Kosuraju G) (letrec ((vertices (remove-duplicates (append (dict-keys G) (append* (dict-values G))))) (visited?-dict (make-hash)) ; or any mutable dict type (assigned-dict (make-hash)) ; or any mutable d...
Give a code snippet in #Racket This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kos...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Phix
Phix
function is_prime_by_trial_division(integer n) if n<2 then return 0 end if if n=2 then return 1 end if if remainder(n,2)=0 then return 0 end if for i=3 to floor(sqrt(n)) by 2 do if remainder(n,i)=0 then return 0 end if end for return 1 end function ?filter(tagset(32),...
Give a code snippet in #Phix Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a p...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#PicoLisp
PicoLisp
(de sumDigits (N Base) (or (=0 N) (+ (% N Base) (sumDigits (/ N Base) Base)) ) )
Give a code snippet in #PicoLisp Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Cind
Cind
  var libsocket = @("lib","socket"); // connect int socket = libsocket.connect("localhost",256); // send data { sheet data = (sheet)"hello socket world"; int datalen = data.size(); int was = libsocket.send(socket,data,0,datalen); // assuming here that all data has been sent (if not, send them in some loop) ...
Give a code snippet in #Cind 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/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#ALGOL_W
ALGOL W
begin  % return the nth Fibonacci number % integer procedure Fibonacci( integer value n ) ; begin integer fn, fn1, fn2; fn2 := 1; fn1 := 0; fn  := 0; for i := 1 until n do begin fn  := fn1 + fn2; fn2 := fn1; ...
Give a code snippet in #ALGOL_W The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions a...
christopher/rosetta-code
http://rosettacode.org/wiki/Mastermind
Mastermind
Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may be repeated in the code The (...
#Perl
Perl
use List::Util qw(any);   print 'Enter pool size, puzzle size, attempts allowed: '; ($pool,$length,$tries) = split /\s+/, <>; $length = 4 if $length eq '' or $length < 3 or $length > 11; $pool = 6 if $pool eq '' or $pool < 2 or $pool > 21; $tries = 10 if $tries eq '' or $tries < 7 or $tries > 21;   @vali...
Give a code snippet in #Perl Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may b...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Lua
Lua
local function haversine(x1, y1, x2, y2) r=0.017453292519943295769236907684886127; x1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1; a = math.pow(math.sin(dx/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c; return d; end
Give a code snippet in #Lua This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equati...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Oz
Oz
declare [Path] = {Module.link ['x-oz://system/os/Path.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   proc {WalkDirTree Root Pattern Proc} proc {Walk R} Entries = {Path.readdir R} Files = {Filter Entries Path.isFile} MatchingFiles = {Filter Files fun {$ File} {Regex.search P...
Give a code snippet in #Oz Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#MAXScript
MAXScript
fn licencesInUse = ( local logFile = openFile "mlijobs.txt" local out = 0 local maxOut = -1 local maxTimes = #()   while not EOF logFile do ( line = readLine logFile   if findString line "OUT" != undefined then ( out += 1 ) else ( ...
Give a code snippet in #MAXScript A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a...
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Klingphix
Klingphix
arg pop nip len dup   ( [get nip] [drop drop "data.txt"] ) if   %f dup "r" fopen !f $f 0 < ( [drop "Could not open '" print print "' for reading" print -1 end ] [drop] ) if   [dup split 3 get tonum 6 > ( [drop print nl] [drop drop] ) if] [$f fgets dup -1 #] while   drop $f fclose   "End " input
Give a code snippet in #Klingphix Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example li...
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
#ERRE
ERRE
  ! Hello World in ERRE language PROGRAM HELLO BEGIN PRINT("Hello world!") END PROGRAM  
Give a code snippet in #ERRE 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/Goldbach%27s_comet
Goldbach's comet
This page uses content from Wikipedia. The original article was at Goldbach's comet. 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) Goldbach's comet is the name given to a plot of the function g(E),...
#ALGOL_68
ALGOL 68
BEGIN # calculate values of the Goldbach function G where G(n) is the number # # of prime pairs that sum to n, n even and > 2 # # generates an ASCII scatter plot of G(n) up to G(2000) # # (Goldbach's Comet) # ...
Give a code snippet in #ALGOL_68 This page uses content from Wikipedia. The original article was at Goldbach's comet. 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) Goldbach's comet is the name giv...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Sidef
Sidef
say "0.1E-5".looks_like_number; #=> true
Give a code snippet in #Sidef Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics A...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Kotlin
Kotlin
// version 1.0.5-2   fun main(args: Array<String>) { val num = 7.125 println("%09.3f".format(num)) }
Give a code snippet in #Kotlin Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Home_primes
Home primes
This page uses content from Wikipedia. The original article was at Home prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, the home prime HP(n) of an integer n greater than 1 is...
#Sidef
Sidef
for n in (2..20, 65) {   var steps = [] var orig = n   for (var f = n.factor; true; f = n.factor) { steps << f n = Num(f.join) break if n.is_prime }   say ("HP(#{orig}) = ", steps.map { .join('_') }.join(' -> ')) }
Give a code snippet in #Sidef This page uses content from Wikipedia. The original article was at Home prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, the home prime HP(n) of...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/2
Text processing/2
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters...
#VBScript
VBScript
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\readings.txt",1) Set objDateStamp = CreateObject("Scripting.Dictionary")   Total_Records = 0 Valid_Records = 0 Duplicate_TimeStamps = ""   Do Until objFile.AtEndOfStream ...
Give a code snippet in #VBScript The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be o...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#Python
Python
import requests import re   response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text languages = re.findall('title="Category:(.*?)">',response)[:-3] # strip last 3   response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text response = re.su...
Give a code snippet in #Python Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#11l
11l
T Edge String start String end Int cost   F (start, end, cost) .start = start .end = end .cost = cost   T Graph [Edge] edges Set[String] vertices   F (edges) .edges = edges.map((s, e, c) -> Edge(s, e, c)) .vertices = Set(.edges.map(e -> e.start)).union(Set(.edges.map(e...
Give a code snippet in #11l This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the si...
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º ...
#Factor
Factor
USING: accessors combinators formatting inverse kernel math math.constants quotations qw sequences units.si ; IN: rosetta-code.angles   ALIAS: degrees arc-deg : gradiens ( n -- d ) 9/10 * degrees ; : mils ( n -- d ) 9/160 * degrees ; : normalize ( d -- d' ) [ 2 pi * mod ] change-value ; CONSTANT: units { degrees gradie...
Give a code snippet in #Factor 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#AutoHotkey
AutoHotkey
Equilibrium_index(list, BaseIndex=0){ StringSplit, A, list, `, Loop % A0 { i := A_Index , Pre := Post := 0 loop, % A0 if (A_Index < i) Pre += A%A_Index% else if (A_Index > i) Post += A%A_Index% if (Pre = Post) Res .= (Res?", ":"") i - (BaseIndex?0:1) } return Res }
Give a code snippet in #AutoHotkey An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A...
christopher/rosetta-code
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#Scala
Scala
class CountingSemaphore(var maxCount: Int) { private var lockCount = 0   def acquire(): Unit = { while ( { lockCount >= maxCount }) wait() lockCount += 1 }   def release(): Unit = { if (lockCount > 0) { lockCount -= 1 notifyAll() } }   def getCount: Int = lockCount }   ...
Give a code snippet in #Scala The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, r...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Lambdatalk
Lambdatalk
  {/ 1 0} -> Infinity {/ 1 Infinity} -> 0 {< {pow 10 100} Infinity} -> true {< {pow 10 1000} Infinity} -> false  
Give a code snippet in #Lambdatalk Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Other...
christopher/rosetta-code
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#REXX
REXX
/*REXX program demonstrates a solution in solving the dining philosophers problem. */ signal on halt /*branches to HALT: (on Ctrl─break).*/ parse arg seed diners /*obtain optional arguments from the CL*/ if datatype(seed, 'W') then call random ,, see...
Give a code snippet in #REXX The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eatin...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Go
Go
package main   import "fmt"   func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs }   func sum(...
Give a code snippet in #Go Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FileName = "Readings.txt"; data = Import[FileName,"TSV"]; Scan[(a=Position[#[[3;;All;;2]],1]; Print["Line:",#[[1]] ,"\tReject:", 24 - Length[a], "\t Accept:", Length[a], "\tLine_tot:", Total@Part[#, Flatten[2*a]] , "\tLine_avg:", Total@Part[#, Flatten[2*a]]/Length[a]])&, data]   GlobalSum = Nb = Running = MaxRunRecorde...
Give a code snippet in #Mathematica.2FWolfram_Language This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by a...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#J
J
lpd =: (1 |.!.1 ])&.q:
Give a code snippet in #J Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Go
Go
func fib(a int) int { if a < 2 { return a } return fib(a - 1) + fib(a - 2) }
Give a code snippet in #Go The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ge...
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "time" )   type holiday struct { time.Time }   func easter(y int) holiday { c := y / 100 n := mod(y, 19) i := mod(c-c/4-(c-(c-17)/25)/3+19*n+15, 30) i -= (i / 28) * (1 - (i/28)*(29/(i+1))*((21-n)/11)) l := i - mod(y+y/4+i+2-c+c/4, 7) m := 3 + (l+40)/44 ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m
Minimum multiple of m where digital sum equals m
Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n. Task Find the first 40 elements of the sequence. Stretch Find the next 30 elements of the sequence. See also OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
#APL
APL
{n←⍵ ⋄ (+∘1)⍣{n=+/10⊥⍣¯1⊢⍺×n}⊢0 } ¨ 7 10⍴⍳70
Give a code snippet in #APL Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n. Task Find the first 40 elements of the sequence. Stretch Find the next 30 elements of the sequence. See also OEIS:A131382 - Minimal number m such that...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Plain_English
Plain English
To run: Start up. Write "Goodbye, world!" on the console without advancing. Wait for the escape key. Shut down.
Give a code snippet in #Plain_English Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello wor...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#J
J
  index=: $ #: I.@:, factorion=: 10&$: :(] = [: +/ [: ! #.^:_1)&>   FACTORIONS=: 9 0 +"1 index Q=: 9 10 11 12 factorion/ i. 1500000   NB. base, factorion expressed in bases 10, and base (,. ".@:((Num_j_,26}.Alpha_j_) {~ #.inv/)"1) FACTORIONS 9 1 1 9 2 2 9 41282 62558 10 1 1 10 ...
Give a code snippet in #J Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Euphoria
Euphoria
function mean(sequence s) atom sum if length(s) = 0 then return 0 else sum = 0 for i = 1 to length(s) do sum += s[i] end for return sum/length(s) end if end function   sequence test test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159} ? mean(test)
Give a code snippet in #Euphoria Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an e...
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
#Common_Lisp
Common Lisp
  VAR b,c: BOOLEAN; ... b := TRUE; c := FALSE; ...  
Give a code snippet in #Common_Lisp 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/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Axe
Axe
Lbl BSEARCH 0→L r₃-1→H While L≤H (L+H)/2→M If {L+M}>r₂ M-1→H ElseIf {L+M}<r₂ M+1→L Else M Return End End -1 Return
Give a code snippet in #Axe A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret num...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Racket
Racket
  #lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen...
Give a code snippet in #Racket Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, M...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Kotlin
Kotlin
// version 1.0.6   import java.util.Scanner   fun main(args: Array<String>) { val command = "cmd /c chcp" val p = Runtime.getRuntime().exec(command) val sc = Scanner(p.inputStream) println(sc.nextLine()) sc.close() }
Give a code snippet in #Kotlin Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Racket
Racket
#lang racket (define (make-initial-state a-list max-i) (for/fold ((state a-list)) ((i (in-range (length a-list) max-i))) (append state (list (- (list-ref state (- i 2)) (list-ref state (- i 1))))))) ;from the seed and 1 creates the initial state   (define (shuffle a-list) (for/list ((i (in-range (le...
Give a code snippet in #Racket A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod ...
christopher/rosetta-code
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#BBC_BASIC
BBC BASIC
REM >penney PRINT "*** Penney's Game ***" REPEAT PRINT ' "Heads you pick first, tails I pick first." PRINT "And it is... "; WAIT 100 ht% = RND(0 - TIME) AND 1 IF ht% THEN PRINT "heads!" PROC_player_chooses(player$) computer$ = FN_optimal(player$) PRINT "I choose "; computer$; "." ELSE PR...
Give a code snippet in #BBC_BASIC Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Head...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#PARI.2FGP
PARI/GP
v=concat(concat([48..57],[65..90]),concat([97..122],95)); apply(Strchr,v)
Give a code snippet in #PARI.2FGP Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a compu...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#J
J
12 *. 18 36 12 *. 18 22 36 132 *./ 12 18 22 396 0 1 0 1 *. 0 0 1 1 NB. for truth valued arguments (0 and 1) it is equivalent to "and" 0 0 0 1 *./~ 0 1 0 0 0 1
Give a code snippet in #J Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has bot...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Java
Java
import java.util.function.Supplier; import java.util.ArrayList;   public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); }   Supplier<Integer> foo = funcs.get(3); Sy...
Give a code snippet in #Java Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2....
christopher/rosetta-code
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#R
R
point_in_polygon <- function(polygon, p) { count <- 0 for(side in polygon) { if ( ray_intersect_segment(p, side) ) { count <- count + 1 } } if ( count %% 2 == 1 ) "INSIDE" else "OUTSIDE" }   ray_intersect_segment <- function(p, side) { eps <- 0.0001 a <- side$A b <- side$B if ( a...
Give a code snippet in #R This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Processing
Processing
boolean SIDESTICK = false; boolean[][] isTaken;   void setup() { size(512, 512); background(0); isTaken = new boolean[width][height]; isTaken[width/2][height/2] = true; }   void draw() { int x = floor(random(width)); int y = floor(random(height)); if (isTaken[x][y]) { return; } while (true) { ...
Give a code snippet in #Processing Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The i...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Raku
Raku
my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;   for <Washington Bush> -> $needle { say "$needle -- { @haystack.first($needle, :k) // 'not in haystack' }"; }
Give a code snippet in #Raku Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#C
C
#include <stdio.h>   int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; // cache factorials from 0 to 11 fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; }   for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); ...
Give a code snippet in #C Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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 Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Action.21
Action!
DEFINE MAXSIZE="200" BYTE ARRAY queue(MAXSIZE) BYTE queueFront=[0],queueRear=[0]   BYTE FUNC IsEmpty() IF queueFront=queueRear THEN RETURN (1) FI RETURN (0)   PROC Push(BYTE v) BYTE rear   rear=queueRear+1 IF rear=MAXSIZE THEN rear=0 FI IF rear=queueFront THEN PrintE("Error: queue is full!") ...
Give a code snippet in #Action.21 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 Implement a FIFO queue. Elements are added at one side and popped from the other in t...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Slate
Slate
define: #Fruit &parents: {Cloneable}. Fruit traits define: #Apple -> Fruit clone. Fruit traits define: #Banana -> Fruit clone. Fruit traits define: #Cherry -> Fruit clone.
Give a code snippet in #Slate Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#PARI.2FGP
PARI/GP
sha256(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha256sum|cut -d' ' -f1`)\"")
Give a code snippet in #PARI.2FGP SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa54271396...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Java
Java
/* Query.java */ public class Query { public static boolean call(byte[] data, int[] length) throws java.io.UnsupportedEncodingException { String message = "Here am I"; byte[] mb = message.getBytes("utf-8"); if (length[0] < mb.length) return false; length[0] = mb.length; System.arraycopy(mb, 0, data, ...
Give a code snippet in #Java This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#JavaScript
JavaScript
  function acceptedBinFormat(bin) { if (bin == 1 || bin === 0 || bin === '0') return true; else return bin; }   function arePseudoBin() { var args = [].slice.call(arguments), len = args.length; while(len--) if (acceptedBinFormat(args[len]) !== true) throw new Error('a...
Give a code snippet in #JavaScript Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#Lua
Lua
function indexOf(haystack, needle) for idx,straw in pairs(haystack) do if straw == needle then return idx end end   return -1 end   function getDigits(n, le, digits) while n > 0 do local r = n % 10 if r == 0 or indexOf(digits, r) > 0 then return fa...
Give a code snippet in #Lua There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ...
christopher/rosetta-code
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. 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 k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Racket
Racket
  #lang racket   ; A tree consists of a point, a left and a right subtree. (struct tree (p l r) #:transparent) ; If the node is in depth d, then the points in l has ; the (d mod k)'th coordinate less than the same coordinate in p.   (define (kdtree d k ps) (cond [(empty? ps) #f] ; #f represents an empty subtree ...
Give a code snippet in #Racket This page uses content from Wikipedia. The original article was at K-d tree. 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 k-d tree (short for k-dimensional tree) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#BlooP
BlooP
  DEFINE PROCEDURE ''DIVIDE'' [A,B]: BLOCK 0: BEGIN IF A < B, THEN: QUIT BLOCK 0; CELL(0) <= 1; OUTPUT <= 1; LOOP AT MOST A TIMES: BLOCK 2: BEGIN IF OUTPUT * B = A, THEN: QUIT BLOCK 0; OUTPUT <= OUTPUT + 1; IF OUTPUT * B > A, THEN: BLOCK 3: BEGIN OUTPUT <= CELL(0); QUIT BLO...
Give a code snippet in #BlooP Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes ...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#FALSE
FALSE
 
Give a code snippet in #FALSE Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Simula
Simula
BEGIN INTEGER PROCEDURE GCD(a, b); INTEGER a, b; BEGIN IF a = 0 THEN a := b ELSE WHILE 0 < b DO BEGIN INTEGER i; i := MOD(a, b); a := b; b := i; END; GCD := a END;   INTEGER a, b;  !outint(SYSOUT.IMAGE.MAIN.LENGTH, 0);!OUTIMAGE;!OUTIMAGE...
Give a code snippet in #Simula Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#68000_Assembly
68000 Assembly
forever: MOVE.B D0,$300001 JMP forever
Give a code snippet in #68000_Assembly Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#PureBasic
PureBasic
Macro reverse(firstIndex, lastIndex) first = firstIndex last = lastIndex While first < last Swap cur(first), cur(last) first + 1 last - 1 Wend EndMacro   Procedure nextPermutation(Array cur(1)) Protected first, last, elementCount = ArraySize(cur()) If elementCount < 1 ProcedureReturn #False...
Give a code snippet in #PureBasic Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Python
Python
''' Bulls and cows. A game pre-dating, and similar to, Mastermind. '''   import random   digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) #print chosen # Debug print '''I have chosen a number from %s unique digits from 1 to 9 arranged in a random order. You need to input a %i digit, unique di...
Give a code snippet in #Python Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the...
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...
#Befunge
Befunge
&>0\0>00p:#v_$ >:#,_ $ @ 4-v >5+#:/#<\55+%:5/\5%: vv_$9+00g+5g\00g8+>5g\00 g>\20p>:10p00g \#v _20gv > 2+ v^-1g01\g5+8<^ +9 _ IVXLCDM
Give a code snippet in #Befunge 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 v...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1 Function GetDivisors(n As Integer) As List(Of Integer) Dim divs As New List(Of Integer) From { 1, n } Dim i = 2 While i * i <= n If n Mod i = 0 Then Dim j = n \ i divs.Add(i) If i <> j Then ...
Give a code snippet in #Visual_Basic_.NET Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on h...
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...
#Unlambda
Unlambda
`ei
Give a code snippet in #Unlambda 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 finaliz...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Logo
Logo
make "suits {Diamonds Hearts Clubs Spades} make "pips {Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King}   to card :n output (sentence item 1 + modulo :n 13 :pips "of item 1 + int quotient :n 13 :suits) end   to new.deck make "deck listtoarray iseq 0 51 make "top 1 end   to swap :i :j :a local...
Give a code snippet in #Logo Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current co...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Go
Go
package main   import ( "bytes" "fmt" )   // Strings in Go allow arbitrary bytes. They are implemented basically as // immutable byte slices and syntactic sugar. This program shows functions // required by the task on byte slices, thus it mostly highlights what // happens behind the syntactic sugar. The prog...
Give a code snippet in #Go Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accordin...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringOrderQ[x_String, y_String] := If[StringLength[x] == StringLength[y], OrderedQ[{x, y}], StringLength[x] >StringLength[y] ] words={"on","sunday","sander","sifted","and","sorted","sambaa","for","a","second"}; Sort[words,StringOrderQ]
Give a code snippet in #Mathematica.2FWolfram_Language 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 |...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#SQL
SQL
  -- save these lines in a file called -- setupworld.sql   -- turn off feedback for cleaner display   SET feedback off   -- 3 x 3 world   -- alive has coordinates of living cells   DROP TABLE alive;   CREATE TABLE alive (x NUMBER,y NUMBER);   -- three alive up the middle -- * -- * -- *   INSERT INTO alive VALUES (...
Give a code snippet in #SQL The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#Swift
Swift
precedencegroup ExponentiationPrecedence { associativity: left higherThan: MultiplicationPrecedence }   infix operator ** : ExponentiationPrecedence   @inlinable public func ** <T: BinaryInteger>(lhs: T, rhs: T) -> T { guard lhs != 0 else { return 1 }   var x = lhs var n = rhs var y = T(1)   while n...
Give a code snippet in #Swift This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show ...
christopher/rosetta-code
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Factor
Factor
USING: combinators formatting generalizations io kernel math math.extras math.functions.integer-logs math.order math.ranges sequences strings tools.memory.private ;   : next ( m -- n ) dup odd? [ dup dup * * ] when integer-sqrt ;   : new-max ( l i h a -- l i h a ) [ drop dup ] 2dip nip dup ;   : (step) ( l i h ...
Give a code snippet in #Factor Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in th...
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,...
#Euphoria
Euphoria
  --Arrays task for Rosetta Code wiki --User:Lnettnay   atom dummy --Arrays are sequences -- single dimensioned array of 10 elements sequence xarray = repeat(0,10) xarray[5] = 5 dummy = xarray[5] ? dummy   --2 dimensional array --5 sequences of 10 elements each sequence xyarray = repeat(repeat(0,10),5) xyarray[3][6] = ...
Give a code snippet in #Euphoria 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 re...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Factor
Factor
"" "/" [ [ "input.txt" "output.txt" move-file "docs" "mydocs" move-file ] with-directory ] bi@
Give a code snippet in #Factor Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the r...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Elena
Elena
import system'io;   public program() { File.assign("output.txt").textwriter().close();   File.assign("\output.txt").textwriter().close();   Directory.assign("docs").create();   Directory.assign("\docs").create(); }
Give a code snippet in #Elena In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty 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/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). 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) Snake is a game where the player maneuvers a line which grows i...
#JavaScript
JavaScript
  const L = 1, R = 2, D = 4, U = 8; var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake; function Snake() { this.length = 1; this.alive = true; this.pos = createVector( 1, 1 ); this.posArray = []; this.posArray.push( createVector( 1, 1 ) ); this.dir = R; this.draw = function() { ...
Give a code snippet in #JavaScript This page uses content from Wikipedia. The original article was at Snake_(video_game). 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) Snake is a game where the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#Sidef
Sidef
module EC {   var A = 0 var B = 7   class Horizon { method to_s { "EC Point at horizon" }   method *(_) { self }   method -(_) { self } }   class Point(Number x, Number y) { method to_s { "EC Poin...
Give a code snippet in #Sidef Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a n...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#langur
langur
val .arr = series 7   writeln " array: ", .arr writeln "filtered: ", where f .x div 2, .arr
Give a code snippet in #langur Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#J
J
encodeLZW =: 4 : 0 d=. ;/x r=.0$0 wc=.w=.{.y for_c. }.y do. wc=.w,c if. d e.~ <wc do. w=.wc else. r=. r, d i.<w d=.d,<wc w=.c end. end. r, d i.<w )
Give a code snippet in #J The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#PowerShell
PowerShell
function triangle($o) { $n = [Math]::Pow(2, $o) $line = ,' '*(2*$n+1) $line[$n] = '█' $OFS = '' for ($i = 0; $i -lt $n; $i++) { Write-Host $line $u = '█' for ($j = $n - $i; $j -lt $n + $i + 1; $j++) { if ($line[$j-1] -eq $line[$j+1]) { $t = ' ' ...
Give a code snippet in #PowerShell Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * *...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#LiveCode
LiveCode
put "pple" into x answer char 2 to len(x) of x // pple answer char 1 to -2 of x // ppl answer char 2 to -2 of x // ppl
Give a code snippet in #LiveCode The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Tcl
Tcl
package require Tcl 8.5   # Produce information about the days in a month, without any assumptions about # what those days actually are. proc calMonthDays {timezone locale year month} { set days {} set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \ -timezone $timezone -locale $locale -form...
Give a code snippet in #Tcl Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with ac...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Nim
Nim
import math, tables   type Quaternion* = object a, b, c, d: float   func initQuaternion*(a, b, c, d = 0.0): Quaternion = Quaternion(a: a, b: b, c: c, d: d)   func `-`*(q: Quaternion): Quaternion = initQuaternion(-q.a, -q.b, -q.c, -q.d)   func `+`*(q: Quaternion; r: float): Quaternion = initQuaternion(q.a + r, q...
Give a code snippet in #Nim Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number mi...
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;...
#Ruby
Ruby
def middle_three_digits(num) # minus sign doesn't factor into digit count, # and calling #abs acts as a duck-type assertion num = num.abs   # convert to string and find length length = (str = num.to_s).length   # check validity raise ArgumentError, "Number must have at least three digits" if length < 3 ...
Give a code snippet in #Ruby Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tes...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#dc
dc
0 si [i = 0]sz [2Q]sA [A = code to break loop]sz [ li 1 + p [print it = i + 1]sz d si [i = it, leave it on stack]sz 6 % 0 =A [call A if 0 == it % 6]sz 0 0 =B [continue loop]sz ]sB 0 0 =B
Give a code snippet in #dc Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Down...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o...
#Sidef
Sidef
func evolve(rule, bin) { var offset = 0 var (l='', r='') Inf.times { bin.sub!(/^((.)\g2*)/, {|_s1, s2| l = s2; offset -= s2.len; s2*2 }) bin.sub!(/(.)\g1*$/, {|s1| r = s1; s1*2 }) printf("%5d| %s%s\n", offset, ' ' * (40 + offset), bin.tr('01','.#')) bin = [l*3, 0.to(bin.len-3...
Give a code snippet in #Sidef The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Erlang
Erlang
divcount(N) -> divcount(N, 1, 0).   divcount(N, D, Count) when D*D > N -> Count; divcount(N, D, Count) -> Divs = case N rem D of 0 -> case N - D*D of 0 -> 1; _ -> 2 end; _ -> 0 end, divcount(N, D + 1, Count + Divs).     antiprimes(N) ->...
Give a code snippet in #Erlang The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#Go
Go
package main   import "fmt"   type dlNode struct { string next, prev *dlNode }   type dlList struct { head, tail *dlNode }   func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p...
Give a code snippet in #Go Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Elem...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Picat
Picat
main =>  % - String assignment S1 = "binary_string", println(s1=S1),    % Picat has re-assignments (:=/2) as well, S1 := "another string", println(s1=S1),    % - String comparison if S1 == "another string" then println(same) else println(not_same) end,    % - String cloning and copying S2 =...
Give a code snippet in #Picat Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accor...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#JavaScript
JavaScript
//Constructor function. function Car(brand, weight) { this.brand = brand; this.weight = weight || 1000; // Resort to default value (with 'or' notation). } Car.prototype.getPrice = function() { // Method of Car. return this.price; }   function Truck(brand, size) { this.car = Car; this.car(brand, 2000); // Call...
Give a code snippet in #JavaScript In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of th...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#OCaml
OCaml
#load "unix.cma"   let lang = "en" (* language: English *)   let usage () = Printf.printf "Usage:\n%s\n" Sys.argv.(0)   let month_pattern = [ [ 0; 4; 8 ]; [ 1; 5; 9 ]; [ 2; 6; 10 ]; [ 3; 7; 11 ];   (* [ 0; 1; 2; 3; 4; 5 ]; [ 6; 7; 8; 9; 10; 11 ];   [ 0; 1; 2; ...
Give a code snippet in #OCaml Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Prolog
Prolog
halve(X,Y) :- Y is X // 2. double(X,Y) :- Y is 2*X. is_even(X) :- 0 is X mod 2.   % columns(First,Second,Left,Right) is true if integers First and Second % expand into the columns Left and Right, respectively columns(1,Second,[1],[Second]). columns(First,Second,[First|Left],[Second|Right]) :- halve(First,Halved), ...
Give a code snippet in #Prolog Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   myVals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ] mySet = Set mySet = HashSet()   loop val over myVals mySet.add(val) end val   loop val over mySet say val end val   return  
Give a code snippet in #NetRexx This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task ...
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...
#REXX
REXX
/*REXX pgm simulates scenarios for a two─bullet Russian roulette game with a 6 cyl. gun.*/ parse arg cyls tests seed . /*obtain optional arguments from the CL*/ if cyls=='' | cyls=="," then cyls= 6 /*Not specified? Then use the default.*/ if tests=='' | tests=="," then tests= 100000 ...
Give a code snippet in #REXX 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/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#C
C
file main.c
Give a code snippet in #C Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input...
christopher/rosetta-code