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/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.
#Neko
Neko
/** Sockets in Neko Tectonics: nekoc sockets.neko sudo nc -vulp 256 & sudo neko sockets */   var socket_init = $loader.loadprim("std@socket_init", 0); var socket_new = $loader.loadprim("std@socket_new", 1); var host_resolve = $loader.loadprim("std@host_resolve", 1); var socket_connect = $loader.loadprim("std@so...
Give a code snippet in #Neko 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/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not...
#Raku
Raku
class SNUSP {   has @!inst-pointer; has @!call-stack; has @!direction; has @!memory; has $!mem-pointer;   method run ($code) { init(); my @code = pad( |$code.lines ); for @code.kv -> $r, @l { my $index = @l.grep( /'$'/, :k ); if $index { ...
Give a code snippet in #Raku Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#C
C
  #include <X11/Xlib.h> void get_pixel_color (Display *d, int x, int y, XColor *color) { XImage *image; image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap); color->pixel = XGetPixel (image, 0, 0); XFree (image); XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), color...
Give a code snippet in #C Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Kotlin
Kotlin
fun main(args: Array<String>) { val s = "" println(s.isEmpty()) // true println(s.isNotEmpty()) // false println(s.length) // 0 println(s.none()) // true println(s.any()) // false }
Give a code snippet in #Kotlin Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Dc
Dc
!clear
Give a code snippet in #Dc Task Clear the terminal window.
christopher/rosetta-code
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ...
#Rust
Rust
use std::env; use std::process; use std::collections::HashMap;   fn main() {   let units: HashMap<&str, f32> = [("arshin",0.7112),("centimeter",0.01),("diuym",0.0254),("fut",0.3048),("kilometer",1000.0),("liniya",0.00254),("meter",1.0),("milia",7467.6),("piad",0.1778),("sazhen",2.1336),("tochka",0.000254),("vershok",0...
Give a code snippet in #Rust Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and r...
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 ...
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(N) ENTRY TO FIB. A = 0 B = 1 THROUGH LOOP, FOR N=N, -1, N.E.0 C = A + B A = B LOOP B = C FUNCTION RETURN A END OF FUNCTION   THROUGH SHOW,...
Give a code snippet in #MAD 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 g...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Go
Go
$ convert plasma.gif -coalesce plasma2.gif $ eog plasma2.gif
Give a code snippet in #Go The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Com...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Truncate[file_, n_] := Module[{filename = file, nbbytes = n, temp}, temp = $TemporaryPrefix <> filename; BinaryWrite[temp, BinaryReadList[filename, "Byte", nbbytes]]; Close[temp]; DeleteFile[filename]; RenameFile[temp, filename]; ]
Give a code snippet in #Mathematica.2FWolfram_Language 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 met...
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.
#Vedit_macro_language
Vedit macro language
// In current directory File_Open("input.txt") Ins_Char(' ') Del_Char(-1) Buf_Close() File_Mkdir("docs")   // In the root directory File_Open("/input.txt") Ins_Char(' ') Del_Char(-1) Buf_Close() File_Mkdir("/docs")
Give a code snippet in #Vedit_macro_language 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/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#Lua
Lua
- constants use UPCASE_SNAKE - variable names use lower_case_snake - class-like structures use CamelCase - other functions use smallCamelCase - Use _ for unneeded variables - Don't use Hungarian Notation
Give a code snippet in #Lua Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#AppleScript
AppleScript
(* Uses a Foundation number formatter for brevity. *) use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation"   on getNumberFormatter(localeID, numberStyle) set formatter to current application's class "NSNumberFormatter"'s new() tell formatter to setLocale:(current applicatio...
Give a code snippet in #AppleScript Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the coun...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Run_BASIC
Run BASIC
dim cards(52) for i = 1 to 52 ' make deck cards(i) = i next   for i = 52 to 1 step -1 ' shuffle deck r = int((rnd(1)*i) + 1) if r <> i then hold = cards(r) cards(r) = cards(i) cards(i) = hold end if next   print "== Shuffled Cards ==" ' print shuffled cards for i =...
Give a code snippet in #Run_BASIC The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging fro...
christopher/rosetta-code
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). 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...
#Phix
Phix
-- -- demo\rosetta\SOAP.exw -- ===================== -- -- translated from https://gist.github.com/p120ph37/8281362ae9da042f3043 -- without js -- (libcurl) include builtins\libcurl.e include builtins\xml.e -- xml_encode() function write_callback(atom pData, integer size, nmemb, atom /*pUserdata*/) integer by...
Give a code snippet in #Phix In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect onc...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Maple
Maple
lexEqual := proc(lst) local i: for i from 2 to numelems(lst) do if lst[i-1] <> lst[i] then return false: fi: od: return true: end proc: lexAscending := proc(lst) local i: for i from 2 to numelems(lst) do if StringTools:-Compare(lst[i],lst[i-1]) then return false: fi: od: return true: end proc: tst := ["abc"...
Give a code snippet in #Maple Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false ...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   #define USE_FAKES 1   const char *states[] = { #if USE_FAKES "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Ha...
Give a code snippet in #C 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 rearra...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#BASIC
BASIC
DIM i(1 TO 10) AS DOUBLE, L0 AS LONG FOR L0 = 1 TO 10 i(L0) = L0 NEXT PRINT STR$(rms#(i()))   FUNCTION rms# (what() AS DOUBLE) DIM L0 AS LONG, tmp AS DOUBLE, rt AS DOUBLE FOR L0 = LBOUND(what) TO UBOUND(what) rt = rt + (what(L0) ^ 2) NEXT tmp = UBOUND(what) - LBOUND(what) + 1 rms# = SQR(...
Give a code snippet in #BASIC Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#R
R
  rm(list=ls()) library(RColorBrewer)     # Create tic.tac.toe function.     tic.tac.toe <- function(name="Name", mode=0, type=0){   place.na <<- matrix(1:9, 3, 3) value <<- matrix(-3, 3, 3) k <<- 1 ; r <<- 0     # Make game board.     image(1:3, 1:3, matrix(sample(9), 3, 3), asp=c(1, 1), xaxt="n", ...
Give a code snippet in #R Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Ti...
christopher/rosetta-code
http://rosettacode.org/wiki/Diversity_prediction_theorem
Diversity prediction theorem
The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the i...
#C
C
    #include<string.h> #include<stdlib.h> #include<stdio.h>   float mean(float* arr,int size){ int i = 0; float sum = 0;   while(i != size) sum += arr[i++];   return sum/size; }   float variance(float reference,float* arr, int size){ int i=0; float* newArr = (float*)malloc(size*sizeof(float));   for(;i<size;i+...
Give a code snippet in #C The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that as...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Jsish
Jsish
/* Matrix exponentiation, in Jsish */ require('Matrix');   if (Interp.conf('unitTest')) { var m = new Matrix([[3, 2], [2, 1]]); ; m; ; m.exp(0); ; m.exp(1); ; m.exp(2); ; m.exp(4); ; m.exp(10); }   /* =!EXPECTSTART!= m ==> { height:2, mtx:[ [ 3, 2 ], [ 2, 1 ] ], width:2 } m.exp(0) ==> { height:2, ...
Give a code snippet in #Jsish Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#Sidef
Sidef
var victims = [ :fly: " I don't know why S—", :spider: " That wriggled and jiggled and tickled inside her.", :bird: " How absurd, T!", :cat: " Fancy that, S!", :dog: " What a hog, T!", :goat: " She just opened her throat, and in walked the goat!", :cow: " I don't know ...
Give a code snippet in #Sidef Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#D
D
import std.stdio;   int chowla(int n) { int sum; for (int i = 2, j; i * i <= n; ++i) { if (n % i == 0) { sum += i + (i == (j = n / i) ? 0 : j); } } return sum; }   bool[] sieve(int limit) { // True denotes composite, false denotes prime. // Only interested in odd numb...
Give a code snippet in #D Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#sed
sed
#!/bin/sed -rf # Convert to uppercase s/.*/\U&/ # Add lookup table s/$/\nA.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--../ # Main loop :a s/([A-Z])([^\n]*\n.*\1([-.]+))/\3 \2/ ta # Remove lookup table s/\n.*//
Give a code snippet in #sed Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore u...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Nial
Nial
fact is recur [ 0 =, 1 first, pass, product, -1 +]
Give a code snippet in #Nial Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#11l
11l
Deque[Int] s V seed = 292929   s.append(seed) s.append(1)   L(n) 2..54 s.append((s[n - 2] - s[n - 1]) % 10 ^ 9)   Deque[Int] r L(n) 55 V i = (34 * (n + 1)) % 55 r.append(s[i])   F py_mod(a, b) R ((a % b) + b) % b   F getnextr()  :r.append(py_mod((:r[0] - :r[31]), 10 ^ 9))  :r.pop_left() R :r[54]   L ...
Give a code snippet in #11l 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}...
christopher/rosetta-code
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#J
J
insert=:{{ 'R';'';y;a: : if. 0=#y do. insert x elseif. 0=L.y do. x insert insert y else. 'C e K w'=. y select. *x - K case. _1 do. balance C;(x insert e);K;<w case. 0 do. y case. 1 do. balance C;e;K;<x insert w end. end. }}   NB. C: color, e: east, K: key, w: west NB. two casc...
Give a code snippet in #J Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, imple...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Raku
Raku
sub MAIN ($filename = 'default.ppm') {   my $in = open($filename, :r, :enc<iso-8859-1>) or die $in;   my ($type, $dim, $depth) = $in.lines[^3];   my $outfile = $filename.subst('.ppm', '.pgm'); my $out = open($outfile, :w, :enc<iso-8859-1>) or die $out;   $out.say("P5\n$dim\n$depth");   for $in.l...
Give a code snippet in #Raku Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. ...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Ring
Ring
  # Project : CalmoSoft Fifteen Puzzle Game # Date  : 2018/12/01 # Author  : Gal Zsolt (CalmoSoft), Bert Mariani # Email  : calmosoft@gmail.com   load "guilib.ring"   app1 = new qapp {   stylefusionblack() empty = 16 nr_moves = 0 nr_sleep = 1 button_size = 4 curren...
Give a code snippet in #Ring Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603...
#Delphi
Delphi
  program OpenWebNet_password;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function ownCalcPass(password, nonce: string): Cardinal; begin var start := True; var num1 := 0; var num2 := num1; var i := password.ToInteger(); var pwd := i;   for var c in nonce do begin if c <> '0' then begin ...
Give a code snippet in #Delphi Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as fol...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size_distribution
File size distribution
Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no...
#Perl
Perl
use File::Find; use List::Util qw(max);   my %fsize; $dir = shift || '.'; find(\&fsize, $dir);   $max = max($max,$fsize{$_}) for keys %fsize; $total += $size while (undef,$size) = each %fsize;   print "File size distribution in bytes for directory: $dir\n"; for (0 .. max(keys %fsize)) { printf "# files @ %4sb %8s: ...
Give a code snippet in #Perl Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a ...
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...
#Lingo
Lingo
-- String creation and destruction foo = "Hello world!" -- created by assignment; destruction via garbage collection   -- Strings are binary safe put numtochar(0) into char 6 of foo put chartonum(foo.char[6]) -- 0 put str.char[7..foo.length] -- "world!"   -- String cloning and copying bar = foo -- copies foo contents t...
Give a code snippet in #Lingo 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/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Vala
Vala
struct Point{ int x; int y; Point(int px,int py){ x=px; y=py; } }   public class Hilbert : Gtk.DrawingArea {   private int it = 1; private Point[] points; private const int WINSIZE = 300;   public Hilbert() { set_size_request(WINSIZE, WINSIZE); }   public ...
Give a code snippet in #Vala Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#C.23
C#
using System; using System.Collections.Generic;   public class Program { public static IEnumerable<int[]> Combinations(int m, int n) { int[] result = new int[m]; Stack<int> stack = new Stack<int>(); stack.Push(0);   while (stack.Count > 0) { ...
Give a code snippet in #C.23 Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#MATLAB
MATLAB
function step_up() while ~step() step_up(); end
Give a code snippet in #MATLAB From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function de...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT   system=SYSTEM ()   IF (system=="WIN") THEN SET to="name@domain.org" SET cc="name@domain.net" subject="test" text=* DATA how are you?   status = SEND_MAIL (to,cc,subject,text,-)   ENDIF  
Give a code snippet in #TUSCRIPT Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are give...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Matrix is generic type Element is private; Zero : Element; One  : Element; with function "+" (A, B : Element) return Element is <>; with function "*" (A, B : Element) return Element is <>; with function Image (X : Element) retur...
Give a code snippet in #Ada Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#ACL2
ACL2
(defun insert (x xs) (cond ((endp xs) (list x)) ((> x (first xs)) (cons (first xs) (insert x (rest xs)))) (t (cons x xs))))   (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs)))))   (defun stem-and-leaf-bins (xs bin curr) (cond ((endp xs) (list cu...
Give a code snippet in #ACL2 Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Bash
Bash
#! /bin/bash declare -a encodeTable=( # + , - . / 0 1 2 3 4 5 6 7 8 9  : 62 -1 -1 -1 63 52 53 54 55 56 57 58 59 60 61 -1 # ; < = >  ? @ A B C D E F G H I J -1 -1 -1 -1 -1 -1 0 1 2 3 4 5 6 7 8 9 # K L M N O P ...
Give a code snippet in #Bash See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#Pascal
Pascal
Program Example40; {$IFDEF FPC} {$MOde objFPC} {$ENDIF} { Program to demonstrate the randg function. } Uses Math;   type tTestData = extended;//because of math.randg ttstfunc = function (mean, sd: tTestData): tTestData; tExArray = Array of tTestData; tSolution = record SolExArr : tExArray; ...
Give a code snippet in #Pascal The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform rando...
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...
#SNOBOL4
SNOBOL4
"knight" len(1) rem . output  ;* strip first character "socks" rtab(1) . output  ;* strip last character "brooms" len(1) rtab(1) . output  ;* strip both first and last characters
Give a code snippet in #SNOBOL4 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/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Visual_Basic_.NET
Visual Basic .NET
Module Program Sub Main() Dim days = New String(11) {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"} Dim gifts = New String(11) { "A partridge in a pear tree", "Two turtle doves", "Three french ...
Give a code snippet in #Visual_Basic_.NET Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to stri...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Icon_and_Unicon
Icon and Unicon
procedure main() stack := [] # new empty stack push(stack,1) # add item push(stack,"hello",table(),set(),[],5) # add more items of mixed types in order left to right y := top(stack) # peek x := pop(stack) ...
Give a code snippet in #Icon_and_Unicon 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The s...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Maple
Maple
  f := proc (n, m) local fac, i; fac := 1; for i from n by -m to 1 do fac := fac*i; end do; return fac; end proc:   a:=Matrix(5,10): for i from 1 to 5 do for j from 1 to 10 do a[i,j]:=f(j,i); end do; end do; a;  
Give a code snippet in #Maple The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#COBOL
COBOL
>>SOURCE FORMAT IS FREE IDENTIFICATION DIVISION. PROGRAM-ID. comma-quibbling-test.   ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION comma-quibbling . DATA DIVISION. WORKING-STORAGE SECTION. 01 strs-area. 03 strs-len PIC 9. 03 strs PIC X(...
Give a code snippet in #COBOL Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An in...
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...
#Applesoft_BASIC
Applesoft BASIC
0 A = ABS(INT(A)) 1 B = ABS(INT(B)) 2 GCD = A * NOT NOT B 3 FOR B = B + A * NOT B TO 0 STEP 0 4 A = GCD 5 GCD = B 6 B = A - INT (A / GCD) * GCD 7 NEXT B
Give a code snippet in #Applesoft_BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Icon_and_Unicon
Icon and Unicon
procedure main() local lst lst := [10, 20, 30, 40] myfun(callback, lst) end   procedure myfun(fun, lst) every fun(!lst) end   procedure callback(arg) write("->", arg) end
Give a code snippet in #Icon_and_Unicon Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#DWScript
DWScript
PrintLn(Ord('a')); PrintLn(Chr(97));
Give a code snippet in #DWScript Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). C...
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
#Julia
Julia
ls = readstring(`ls`)
Give a code snippet in #Julia 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/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...
#Julia
Julia
using Memoize   @memoize function scs(x, y) if x == "" return y elseif y == "" return x elseif x[1] == y[1] return "$(x[1])$(scs(x[2:end], y[2:end]))" elseif length(scs(x, y[2:end])) <= length(scs(x[2:end], y)) return "$(y[1])$(scs(x, y[2:end]))" else return "...
Give a code snippet in #Julia 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Go
Go
package main   import ( "fmt" "strings" )   func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) }   func solve(board string) string { buffer = make([]byte, len(board)) width :...
Give a code snippet in #Go Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character arr...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#BBC_BASIC
BBC BASIC
REM >multifact FOR i% = 1 TO 5 PRINT "Degree "; i%; ":"; FOR j% = 1 TO 10 PRINT " ";FNmultifact(j%, i%); NEXT PRINT NEXT END : DEF FNmultifact(n%, degree%) LOCAL i%, mfact% mfact% = 1 FOR i% = n% TO 1 STEP -degree% mfact% = mfact% * i% NEXT = mfact%
Give a code snippet in #BBC_BASIC The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Raku
Raku
sub is_vampire (Int $num) { my $digits = $num.comb.sort; my @fangs; (10**$num.sqrt.log(10).floor .. $num.sqrt.ceiling).map: -> $this { next if $num % $this; my $that = $num div $this; next if $this %% 10 && $that %% 10; @fangs.push("$this x $that") if ($this ~ $that).comb.sor...
Give a code snippet in #Raku A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   t...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Delphi
Delphi
  program Key_Bindings_test;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, Winapi.Windows, Messages, Classes;   type // Class of application without window TWindowlessApplication = class private Terminated: Boolean; F7_id: Word; F6_id: Word; WIN_A: Word; procedure HandleMes...
Give a code snippet in #Delphi Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#QB64
QB64
$NOPREFIX PRINT DIREXISTS("docs") PRINT DIREXISTS("\docs") PRINT FILEEXISTS("input.txt") PRINT FILEEXISTS("\input.txt")
Give a code snippet in #QB64 Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#LOLCODE
LOLCODE
I HAS A SRS "Δ" ITZ 1 SRS "Δ" R SUM OF SRS ":(394)" AN 1 VISIBLE SRS ":[GREEK CAPITAL LETTER DELTA]"
Give a code snippet in #LOLCODE Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Julia
Julia
using Printf   function _menu(items) for (ind, item) in enumerate(items) @printf "  %2i) %s\n" ind item end end   _ok(::Any,::Any) = false function _ok(reply::AbstractString, itemcount) n = tryparse(Int, reply) return isnull(n) || 0 ≤ get(n) ≤ itemcount end   "Prompt to select an item from the i...
Give a code snippet in #Julia Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the stri...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Oz
Oz
declare proc {InsertionSort A} Low = {Array.low A} High = {Array.high A} in for I in Low+1..High do Value = A.I J = {NewCell I-1} in for while:@J >= Low andthen A.@J > Value do A.(@J+1) := A.@J J := @J - 1 end A.(@J+1) := Value e...
Give a code snippet in #Oz Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#ALGOL_68
ALGOL 68
PR read "file.a68" PR
Give a code snippet in #ALGOL_68 Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#OCaml
OCaml
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col);...
Give a code snippet in #OCaml Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interp...
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...
#Phix
Phix
if error_code!=NO_ERROR then abort(0) end if
Give a code snippet in #Phix Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Phix
Phix
function Mertens(integer n) integer res = 1 for k=2 to n do res -= Mertens(floor(n/k)) end for return res end function sequence s = {" ."} for i=1 to 143 do s = append(s,sprintf("%3d",Mertens(i))) end for puts(1,join_by(s,1,12," ")) integer prev = 1, zeroes = 0, crosses = 0 for n=2 to 1000 do...
Give a code snippet in #Phix The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius...
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...
#Nim
Nim
var funcs: seq[proc(): int] = @[]   for i in 0..9: (proc = let x = i funcs.add(proc (): int = x * x))()   for i in 0..8: echo "func[", i, "]: ", funcs[i]()
Give a code snippet in #Nim 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/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: ...
#Racket
Racket
  (define (RK4 F δt) (λ (t y) (define δy1 (* δt (F t y))) (define δy2 (* δt (F (+ t (* 1/2 δt)) (+ y (* 1/2 δy1))))) (define δy3 (* δt (F (+ t (* 1/2 δt)) (+ y (* 1/2 δy2))))) (define δy4 (* δt (F (+ t δt) (+ y δy1)))) (list (+ t δt) (+ y (* 1/6 (+ δy1 (* 2 δy2) (* 2 δy3) δy4))))))  
Give a code snippet in #Racket 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 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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
    public class BogoSort { public static void main(String[] args) { //Enter array to be sorted here int[] arr={4,5,6,0,7,8,9,1,2,3};   BogoSort now=new BogoSort(); System.out.print("Unsorted: "); now.display1D(arr);   now.bogo(arr);   System.out.print("Sorted: "); now.display1D(arr); } void bogo(i...
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/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#CLIPS
CLIPS
(deffunction S (?x) (/ 1 (* ?x ?x))) (deffunction partial-sum-S (?start ?stop) (bind ?sum 0) (loop-for-count (?i ?start ?stop) do (bind ?sum (+ ?sum (S ?i))) ) (return ?sum) )
Give a code snippet in #CLIPS Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#Kotlin
Kotlin
// version 1.1.4-3   import java.io.File   val r = Regex("[ ]+")   fun main(args: Array<String>) { val lines = File("days_of_week.txt").readLines() for ((i, line) in lines.withIndex()) { if (line.trim().isEmpty()) { println() continue } val days = line.trim().spli...
Give a code snippet in #Kotlin The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or de...
christopher/rosetta-code
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Processing
Processing
int l = 300;   void setup() { size(400, 400); background(0, 0, 255); stroke(255); // draw from center of screen translate(width/2.0, height/2.0); // center curve from lower-left corner of base equilateral triangle translate(-l/2.0, l*sqrt(3)/6.0); for (int i = 1; i <= 3; i++) { kcurve(0, l); rot...
Give a code snippet in #Processing Draw a Koch curve. See details: Koch curve
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Pop11
Pop11
;;; Setup token reader vars itemrep; incharitem(charin) -> itemrep; ;;; read the numbers lvars a = itemrep(), b = itemrep(); ;;; Print results printf(a + b, 'a + b = %p\n'); printf(a - b, 'a - b = %p\n'); printf(a * b, 'a * b = %p\n'); printf(a div b, 'a div b = %p\n'); printf(a mod b, 'a mod b = %p\n');
Give a code snippet in #Pop11 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#VBScript
VBScript
Function RegExTest(str,patrn) Dim regEx Set regEx = New RegExp regEx.IgnoreCase = True regEx.Pattern = patrn RegExTest = regEx.Test(str) End Function   Function URLDecode(sStr) Dim str,code,a0 str="" code=sStr code=Replace(code,"+"," ") While len(code)>0 If InStr(code,"%"...
Give a code snippet in #VBScript This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencod...
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...
#Rust
Rust
use std::net::{Shutdown, TcpListener}; use std::thread; use std::io::Write;   const RESPONSE: &'static [u8] = b"HTTP/1.1 200 OK\r Content-Type: text/html; charset=UTF-8\r\n\r <!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title> <style>body { background-color: #111 } h1 { font-size:4cm; text-align: center; col...
Give a code snippet in #Rust 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Fhidwfe
Fhidwfe
  function listint scanint (num:ptr) {// as of writing, fhidwfe has no builtin int scanning reset negative read = num num1 = 0 num2 = 0 while ~ = deref_ubyte$ read ' ' { char = deref_ubyte$ read if = char '-' { set negative } { num1 = + * 10 num1 as - char '0' int } read = + read 1u } if negative...
Give a code snippet in #Fhidwfe A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separa...
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...
#Salmon
Salmon
for (x; 10; x >= 0; -1) x!;
Give a code snippet in #Salmon 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/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Inform_7
Inform 7
Enter Two Numbers is a room.   Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.   The first number is a number that varies.   After numerically entering for the first time: now the first number is the number understood.   After numerically entering for the second...
Give a code snippet in #Inform_7 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Elixir
Elixir
  defmodule Josephus do def find(n,k) do find(Enum.to_list(0..n-1),0..k-2,k..n) end   def find([_|[r|_]],_,_..d) when d < 3 do IO.inspect r end   def find(arr,a..c,b..d) when length(arr) >= 3 do find(Enum.slice(arr,b..d) ++ Enum.slice(arr,a..c),a..c,b..d-1) end end   Josephus.find(41,3)  
Give a code snippet in #Elixir Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Picat
Picat
main => Words = read_file_lines("unixdict.txt"), IEWords = [Word : Word in Words, find(Word,"ie",_,_)], EIWords = [Word : Word in Words, find(Word,"ei",_,_)],    % cie vs not cie [CIE_len, CIE_not_len] = partition_len(IEWords,"cie"), println([cie=CIE_len,cie_not=CIE_not_len]),    % cei vs not cei [CEI_...
Give a code snippet in #Picat The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individuall...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Modula-3
Modula-3
MODULE FileIO EXPORTS Main;   IMPORT IO, Rd, Wr;   <*FATAL ANY*>   VAR infile: Rd.T; outfile: Wr.T; txt: TEXT;   BEGIN infile := IO.OpenRead("input.txt"); outfile := IO.OpenWrite("output.txt"); txt := Rd.GetText(infile, LAST(CARDINAL)); Wr.PutText(outfile, txt); Rd.Close(infile); Wr.Close(outfile); EN...
Give a code snippet in #Modula-3 File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a fil...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Vala
Vala
void recur(uint64 v ) { print (@"$v\n"); recur( v + 1); }   void main() { recur(0); }
Give a code snippet in #Vala Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Icon_and_Unicon
Icon and Unicon
procedure main() write(&progname) # obtain and write out the program name from the keyword &progname end
Give a code snippet in #Icon_and_Unicon The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide t...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#Sidef
Sidef
var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +'   class RPN(arr=[]) {   method binop(op) { var x = arr.pop var y = arr.pop arr << y.(op)(x) }   method run(p) { p.each_word { |w| say "#{w} (#{arr})" given (w) { when (/\d/) { ...
Give a code snippet in #Sidef Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RP...
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 ...
#Action.21
Action!
PROC Main() INT i   FOR i=-1 TO 1 DO IF i<0 THEN PrintF("%I is less than zero%E",i) ELSEIF i>0 THEN PrintF("%I is greater than zero%E",i) ELSE PrintF("%I is zero%E",i) FI OD RETURN
Give a code snippet in #Action.21 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. Com...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Gambas
Gambas
Public Sub Main() Dim sDir As String[] = Dir(User.Home &/ "test").Sort()   Print sDir.Join(gb.NewLine)   End
Give a code snippet in #Gambas Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Examp...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algor...
#Forth
Forth
defer precedes defer exchange   : gnomesort ( a n) swap >r 1 ( n c) begin ( n c) over over > ( n c f) while ( n c) dup if ( n c) dup ...
Give a code snippet in #Forth Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare s...
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...
#8th
8th
    needs map/iter   8 var, numtasks var tasks   0 args "Give filename as param" thrownull f:slurp >s s:len numtasks @ n:/ n:ceil 1 a:close s:/ a:len numtasks ! constant work   m:new constant result   : print-character-count \ m s -- m swap over m:@ rot s:size 1 n:= over -1 s:@ nip 31 n:< and if -1 s:@ n...
Give a code snippet in #8th 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  (assig...
christopher/rosetta-code
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Ring
Ring
  str = [] people = [2,3,5,11]   result = people for i in people str = [] see "" + i + ": " fair(25, i) for n in result add(str,n) next showarray(str) next   func fair n,base   result = list(n) for i=1 to n j = i-1 t = 0 while j>0 t ...
Give a code snippet in #Ring The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs f...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim s As String Dim i AS Integer Input "Please enter a string : "; s Do Input "Please enter 75000  : "; i Loop Until i = 75000 Print Print s, i Sleep
Give a code snippet in #FreeBASIC User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#REXX
REXX
/*REXX program creates (and displays) an HTML table of five rows and three columns.*/ parse arg rows . /*obtain optional argument from the CL.*/ if rows=='' | rows=="," then rows=5 /*no ROWS specified? Then use default.*/ cols = 3 ...
Give a code snippet in #REXX Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#SenseTalk
SenseTalk
put "little" into x   put "Mary had a [[x]] lamb." -- this is a literal string put !"Mary had a [[x]] lamb." -- this is an interpolated string put put !"[[repeat with n=2 to 6]]Mary had [[n]] [[x]] lambs.[[return]][[end repeat]]" put !"Mary had [[repeat with n=2 to 6]][[n]] [[x]] [[end repeat]]lambs."  
Give a code snippet in #SenseTalk Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Clojure
Clojure
(ns lychrel.core (require [clojure.string :as s]) (require [clojure.set :as set-op]) (:gen-class))   (defn palindrome? "Returns true if given number is a palindrome (number on base 10)" [number] (let [number-str (str number)] (= number-str (s/reverse number-str))))   (defn delete-leading-zeros "Delete l...
Give a code snippet in #Clojure   Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to mos...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Racket
Racket
#lang racket   (require racket/fixnum)   (define cache-size 35000000)   (define chowla-cache (make-fxvector cache-size -1))   (define (chowla/uncached n) (for/sum ((i (sequence-filter (λ (x) (zero? (modulo n x))) (in-range 2 (add1 (quotient n 2)))))) i))   (define (chowla n) (if (> n cache-size) (chowla/uncache...
Give a code snippet in #Racket Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Rust
Rust
  use ripemd160::{Digest, Ripemd160};   /// Create a lowercase hexadecimal string using the /// RIPEMD160 hashing algorithm fn ripemd160(text: &str) -> String { // create a lowercase hexadecimal string // using the shortand for the format macro // https://doc.rust-lang.org/std/fmt/trait.LowerHex.html fo...
Give a code snippet in #Rust RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASC...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#PostScript
PostScript
  /compose { % f g -> { g f } [ 3 1 roll exch  % procedures are not executed when encountered directly  % insert an 'exec' after procedures, but not after operators 1 index type /operatortype ne { /exec cvx exch } if dup type /operatortype ne { /exec cvx } if ] cvx } def   /square { dup mul } def /plus1 { 1 ...
Give a code snippet in #PostScript Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function  ...
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...
#AWK
AWK
BEGIN { while(1) { print "SPAM" } }
Give a code snippet in #AWK 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/...
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...
#BBC_BASIC
BBC BASIC
PRINT "Distance = " ; FNhaversine(36.12, -86.67, 33.94, -118.4) " km" END   DEF FNhaversine(n1, e1, n2, e2) LOCAL d() : DIM d(2) d() = COSRAD(e1-e2) * COSRAD(n1) - COSRAD(n2), \ \ SINRAD(e1-e2) * COSRAD(n1), \ \ SINRAD(n1) - SINRAD(n2) = ASN(MOD(d()) / 2) * 6372.8...
Give a code snippet in #BBC_BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Factor
Factor
USING: combinators.short-circuit unicode urls.encoding.private ;   : my-url-encode ( str -- encoded ) [ { [ alpha? ] [ "-._~" member? ] } 1|| ] (url-encode) ;   "http://foo bar/" my-url-encode print
Give a code snippet in #Factor Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#AWK
AWK
# Finds the subsequence of ary[1] to ary[len] with the greatest sum. # Sets subseq[1] to subseq[n] and returns n. Also sets subseq["sum"]. # An empty subsequence has sum 0. function maxsubseq(subseq, ary, len, b, bp, bs, c, cp, i) { b = 0 # best sum c = 0 # current sum bp = 0 # position of best subsequence bn...
Give a code snippet in #AWK Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are ne...
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
#Pict
Pict
(pr "Hello World!");
Give a code snippet in #Pict 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/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Io
Io
List do( quickSort := method( if(size > 1) then( pivot := at(size / 2 floor) return select(x, x < pivot) quickSort appendSeq( select(x, x == pivot) appendSeq(select(x, x > pivot) quickSort) ) ) else(return self) )   quickSortInPlace := meth...
Give a code snippet in #Io Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#C.23
C#
public class Bitmap { public struct Color { public byte Red { get; set; } public byte Blue { get; set; } public byte Green { get; set; } } Color[,] _imagemap; public int Width { get { return _imagemap.GetLength(0); } } public int Height { get { return _imagemap.GetLength(...
Give a code snippet in #C.23 Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB col...
christopher/rosetta-code
http://rosettacode.org/wiki/Jaro_similarity
Jaro similarity
The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an exact match. Definition The...
#D
D
auto jaro(in string s1, in string s2) { int s1_len = cast(int) s1.length; int s2_len = cast(int) s2.length; if (s1_len == 0 && s2_len == 0) return 1;   import std.algorithm.comparison: min, max; auto match_distance = max(s1_len, s2_len) / 2 - 1; auto s1_matches = new bool[s1_len]; auto s2_ma...
Give a code snippet in #D The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an exa...
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.
#PicoLisp
PicoLisp
(println (car (info "input.txt"))) (println (car (info "/input.txt")))
Give a code snippet in #PicoLisp 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