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/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "msgdigest.s7i";   const proc: main is func begin writeln(hex(sha1("Rosetta Code"))); end func;
Give a code snippet in #Seed7 SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to ide...
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...
#Bracmat
Bracmat
( (Δ=1) & 1+!Δ:?Δ & out$("Δ:" !Δ) );
Give a code snippet in #Bracmat 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/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#REXX
REXX
/*REXX pgm draws a Sierpinski triangle by running the chaos game with a million points*/ parse value scrsize() with sd sw . /*obtain the depth and width of screen.*/ sw= sw - 2 /*adjust the screen width down by two. */ sd= sd - 4 ...
Give a code snippet in #REXX The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Fortran
Fortran
program Short_Circuit_Eval implicit none   logical :: x, y logical, dimension(2) :: l = (/ .false., .true. /) integer :: i, j   do i = 1, 2 do j = 1, 2 write(*, "(a,l1,a,l1,a)") "Calculating x = a(", l(i), ") and b(", l(j), ")" ! a AND b x = a(l(i)) if(x) then x = b(l(...
Give a code snippet in #Fortran Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable r...
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...
#C
C
#include <stdio.h>   int main(int argc, char **argv) { printf("Executable: %s\n", argv[0]);   return 0; }
Give a code snippet in #C 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#Ol
Ol
  (define (bubble-sort x ??) (define (sort-step l) (if (or (null? l) (null? (cdr l))) l (if (?? (car l) (cadr l)) (cons (cadr l) (sort-step (cons (car l) (cddr l)))) (cons (car l) (sort-step (cdr l)))))) (let loop ((i x)) (if (equal? i (sort-step i)) ...
Give a code snippet in #Ol 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/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Mirah
Mirah
puts 'code' # I am a comment /* This is * a multiple * line comment */  
Give a code snippet in #Mirah Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#MATLAB_.2F_Octave
MATLAB / Octave
  funName = 'foo'; % generate function name feval (funNAME, ...) % evaluation function with optional parameters   funName = 'a=atan(pi)'; % generate function name eval (funName, 'printf(''Error\n'')')  
Give a code snippet in #MATLAB_.2F_Octave Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Smalltalk
Smalltalk
digitalRoot := [:nr :arIn | r := (nr printString asArray collect:#digitValue) sum. r > 9 ifTrue:[ digitalRoot value:r value:arIn+1. ] ifFalse:[ { arIn+1 . r } ]. ].   #( 627615 39390 588225 393900588225 10 199 199999999999999999999999999999999999999999999999999999999999999999999...
Give a code snippet in #Smalltalk The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X}...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Dim input() = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"} For Each s In input Console.WriteLine($"'{s}' (Length {s.Length}) " + String.Join(", ", s.Select(Function(c, i) (c, i)).GroupBy(Function(t) t.c).Where(Function(g) g.Count() > ...
Give a code snippet in #Visual_Basic_.NET Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Nim
Nim
var n: int = 1024 while n > 0: echo(n) n = n div 2
Give a code snippet in #Nim Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Standard_ML
Standard ML
fun isBalanced s = checkBrackets 0 (String.explode s) and checkBrackets 0 [] = true | checkBrackets _ [] = false | checkBrackets ~1 _ = false | checkBrackets counter (#"["::rest) = checkBrackets (counter + 1) rest | checkBrackets counter (#"]"::rest) = checkBrackets (counter - 1) rest | checkBrackets counter ...
Give a code snippet in #Standard_ML Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which...
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#Kotlin
Kotlin
// version 1.0.6   /* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores and then, if the scores are equal, by reverse alphabetic order of names */   fun standardRanking(scores: Array<Pair<Int, String>>): IntArray { val rankings = IntArray(scores.size...
Give a code snippet in #Kotlin Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#J
J
require'strings convert' urlencode=: rplc&((#~2|_1 47 57 64 90 96 122 I.i.@#)a.;"_1'%',.hfd i.#a.)
Give a code snippet in #J 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#PowerShell
PowerShell
foreach ($n in 0..33) { "Base 2: " + [Convert]::ToString($n, 2) "Base 8: " + [Convert]::ToString($n, 8) "Base 10: " + $n "Base 10: " + [Convert]::ToString($n, 10) "Base 10: " + ("{0:D}" -f $n) "Base 16: " + [Convert]::ToString($n, 16) "Base 16: " + ("{0:X}" -f $n) }
Give a code snippet in #PowerShell Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standar...
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
#Frink
Frink
  cmpFunc = {|a,b| length[a] <=> length[b]}   a = ["tree", "apple", "bee", "monkey", "z"] sort[a, cmpFunc]  
Give a code snippet in #Frink Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclotomic_polynomial
Cyclotomic polynomial
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and print the order of the first 10...
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using IntMap = System.Collections.Generic.Dictionary<int, int>;   public static class CyclotomicPolynomial { public static void Main2() { Console.WriteLine("Task 1: Cyclotomic polynomials for n <= 30:"); for...
Give a code snippet in #C.23 The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and p...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#Phix
Phix
with javascript_semantics function swap(sequence s, integer x1, y1, x2, y2) {s[x1,y1],s[x2,y2]} = {s[x2,y2],s[x1,y1]} return s end function function se_magicsq(integer n) if n<6 or mod(n-2,4)!=0 then crash("illegal size (%d)",{n}) end if sequence sq = repeat(repeat(0,n),n) integer ...
Give a code snippet in #Phix A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Tcl
Tcl
$env(HOME)
Give a code snippet in #Tcl Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the w...
#8080_Assembly
8080 Assembly
puts: equ 9 ; CP/M syscall to print string fopen: equ 15 ; CP/M syscall to open a file fread: equ 20 ; CP/M syscall to read from file FCB1: equ 5Ch ; First FCB (input file) DTA: equ 80h ; Disk transfer address org 100h ;;; Make wheel (2nd argument) lowercase and store it lxi d,DTA+1 ; Start of command line arg...
Give a code snippet in #8080_Assembly A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must co...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Ada
Ada
with Ada.Directories; use Ada.Directories;
Give a code snippet in #Ada Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Scala
Scala
import scala.util.Random import scala.util.control.Breaks._   object Main { def playOptimal(n: Int): Boolean = { val secretList = Random.shuffle((0 until n).toBuffer)   for (i <- secretList.indices) { var prev = i breakable { for (_ <- 0 until secretList.size / 2) { if (secretLis...
Give a code snippet in #Scala The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start o...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Dragon
Dragon
  for value : array { showln value }  
Give a code snippet in #Dragon Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#C.23
C#
using System;   class Program { static void Main(string[] args) { for (int i = 99; i > -1; i--) { if (i == 0) { Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer."); Console.WriteLine("Go to the store and buy s...
Give a code snippet in #C.23 Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Raku
Raku
sub nth-root ($n, $A, $p=1e-9) { my $x0 = $A / $n; loop { my $x1 = (($n-1) * $x0 + $A / ($x0 ** ($n-1))) / $n; return $x1 if abs($x1-$x0) < abs($x0 * $p); $x0 = $x1; } }   say nth-root(3,8);
Give a code snippet in #Raku Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Lua
Lua
require("date")   for year=2008,2121 do if date(year, 12, 25):getweekday() == 1 then print(year) end end
Give a code snippet in #Lua A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 20...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#PARI.2FGP
PARI/GP
  \\ Simple "cuboid". Try different parameters of this Cuboid() function. \\ 4/11/16 aev Cuboid(a,b,c,u=10)={ my(dx,dy,ttl="Cuboid AxBxC: ",size=200,da=a*u,db=b*u,dc=c*u); print(" *** ",ttl,a,"x",b,"x",c,"; u=",u); plotinit(0); plotscale(0, 0,size, 0,size); plotcolor(0,7); \\grey plotmove(0, 0,0); plotrline(0,dc,da\2)...
Give a code snippet in #PARI.2FGP Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projectio...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Printer
Colour pinstripe/Printer
The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence...
#FreeBASIC
FreeBASIC
Dim As String exename #ifdef __FB_WIN32__ exename = "mspaint.exe /pt" #endif #ifdef __FB_LINUX__ exename = "lp -o media=A4 " #endif   Dim As Uinteger ps, col, h, w, x, y1, y2   ' (A4) # 595 x 842 dots w = 842 : h = 595 ' create display size window, 8bit color (palette), no frame Screenres w, h, 8,, 8   h \= 7 :...
Give a code snippet in #FreeBASIC The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be inc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(defun merge-sort (result-type sequence predicate) (let ((split (floor (length sequence) 2))) (if (zerop split) (copy-seq sequence) (merge result-type (merge-sort result-type (subseq sequence 0 split) predicate) (merge-sort result-type (subseq sequence split) predicate)...
Give a code snippet in #Common_Lisp 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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Maple
Maple
printf(" "); for i to 12 do printf("%-3d ", i); end do; printf("\n"); for i to 75 do printf("-"); end do; for i to 12 do printf("\n%2d| ", i); for j to 12 do if j<i then printf(" "); else printf("%-3d ", i * j); end if end do end do
Give a code snippet in #Maple Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#COBOL
COBOL
DISPLAY SPACE WITH BELL
Give a code snippet in #COBOL Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#JavaScript
JavaScript
// modifies the matrix "in place" Matrix.prototype.inverse = function() { if (this.height != this.width) { throw "can't invert a non-square matrix"; }   var I = new IdentityMatrix(this.height); for (var i = 0; i < this.height; i++) this.mtx[i] = this.mtx[i].concat(I.mtx[i]) this....
Give a code snippet in #JavaScript Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . ...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Seed7
Seed7
$ include "seed7_05.s7i";   var integer: maxPathLength is 0; var integer: maxPathLengthCount is 0; var string: maxPathExample is "";   var array string: names is [] ( "audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "dein...
Give a code snippet in #Seed7 A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the ca...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Seed7
Seed7
$ include "seed7_05.s7i"; $ include "keybd.s7i";   const array string: rockPaperScissors is [] ("Rock", "Paper", "Scissors");   const proc: main is func local var char: command is ' '; var integer: user is 0; var integer: comp is 0; begin writeln("Hello, Welcome to rock-paper-scissors"); repeat ...
Give a code snippet in #Seed7 Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#jq
jq
"a " * 3' # => "a a a "
Give a code snippet in #jq Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#JavaScript
JavaScript
function evalArithmeticExp(s) { s = s.replace(/\s/g,'').replace(/^\+/,''); var rePara = /\([^\(\)]*\)/; var exp = s.match(rePara);   while (exp = s.match(rePara)) { s = s.replace(exp[0], evalExp(exp[0])); } return evalExp(s);   function evalExp(s) { s = s.replace(/[\(\)]/g,''); var reMD = /\d+...
Give a code snippet in #JavaScript Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Maple
Maple
a := 1: print ("a is "||a); "a is 1"
Give a code snippet in #Maple Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of...
#Python
Python
from pprint import pprint as pp   def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat   def to_nest(lst, depth=0, level=None): if level is None: ...
Give a code snippet in #Python The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), lis...
christopher/rosetta-code
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#OoRexx
OoRexx
/*REXX pgm beep's "bells" (using PC speaker) when running (perpetually).*/ Parse Arg msg If msg='?' Then Do Say 'Ring a nautical bell' Exit End Signal on Halt /* allow a clean way to stop prog.*/ Do Forever Parse Value time() With hh ':' mn ':' ss ct=time('C') hhmmc=lef...
Give a code snippet in #OoRexx Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slav...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
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 ...
#Ada
Ada
with Ada.Containers.Generic_Array_Sort; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Unchecked_Deallocation;   procedure Sort_List_Identifiers is type Natural_Array is array (Positive range <>) of Natural; type Unbounded_String_Array is array(Positive r...
Give a code snippet in #Ada 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/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Scala
Scala
  import scala.collection.mutable.ListBuffer   object ZeckendorfArithmetic extends App {     val elapsed: (=> Unit) => Long = f => { val s = System.currentTimeMillis   f   (System.currentTimeMillis - s) / 1000 } val add: (Z, Z) => Z = (z1, z2) => z1 + z2 val subtract: (Z, Z) => Z = (z1, z2) => z1 - ...
Give a code snippet in #Scala This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Clojure
Clojure
(.. Runtime getRuntime (exec "cmd /C dir"))
Give a code snippet in #Clojure Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Lua
Lua
io.write("Goodbye, World!")
Give a code snippet in #Lua 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/Standar...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#V
V
"hello" dup
Give a code snippet in #V This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty strin...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Batch_File
Batch File
@echo off setlocal enableDelayedExpansion   set /p "name=Enter a variable name: " set /p "value=Enter a value: " ::Create the variable and set its value set "%name%=%value%" ::Display the value without delayed expansion call echo %name%=%%%name%%% ::Display the value using delayed expansion echo %name%=!%name%!
Give a code snippet in #Batch_File Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#REXX
REXX
/*REXX program performs some operations on quaternion type numbers and displays results*/ q = 1 2 3 4  ; q1 = 2 3 4 5 r = 7  ; q2 = 3 4 5 6 call qShow q , 'q' call qShow q1 ...
Give a code snippet in #REXX Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number m...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#F.23
F#
  // A function to generate department numbers. Nigel Galloway: May 2nd., 2018 type dNum = {Police:int; Fire:int; Sanitation:int} let fN n=n.Police%2=0&&n.Police+n.Fire+n.Sanitation=12&&n.Police<>n.Fire&&n.Police<>n.Sanitation&&n.Fire<>n.Sanitation List.init (7*7*7) (fun n->{Police=n%7+1;Fire=(n/7)%7+1;Sanitation=(n/49...
Give a code snippet in #F.23 There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (dif...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Befunge
Befunge
v 1 >$0 v v < >&:19+`|v < >v 5 6 7 8 ^ \ <>09p19p>09g+09p:|>2*:19+%19g+19p19+/19g+19p:| 2 3 4 > v v"invalid"<10 9 |%+91+g91g90< ...
Give a code snippet in #Befunge The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order ...
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...
#Sidef
Sidef
func knuth_shuffle(a) { for i (a.len ^.. 1) { var j = i.irand a[i, j] = a[j, i] } return a }   say knuth_shuffle(@(1..10))
Give a code snippet in #Sidef 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Icon_and_Unicon
Icon and Unicon
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
Give a code snippet in #Icon_and_Unicon The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of th...
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...
#REXX
REXX
/*REXX program (state name puzzle) rearranges two state's names ──► two new states. */ !='Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia,', 'Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, ',...
Give a code snippet in #REXX Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Ada
Ada
with Accumulator; with Ada.Text_IO; use Ada.Text_IO;   procedure Example is package A is new Accumulator; package B is new Accumulator; begin Put_Line (Integer'Image (A.The_Function (5))); Put_Line (Integer'Image (B.The_Function (3))); Put_Line (Float'Image (A.The_Function (2.3))); end;
Give a code snippet in #Ada A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passe...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
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 |...
#Ruby
Ruby
str = 'abcdefgh' n = 2 m = 3 puts str[n, m] #=> cde puts str[n..m] #=> cd puts str[n..-1] #=> cdefgh puts str[0..-2] #=> abcdefg puts str[str.index('d'), m] #=> def puts str[str.index('de'), m] #=> def puts str[/a.*d/] #=> abcd
Give a code snippet in #Ruby 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Scheme
Scheme
((lambda (s) (display (list s (list (quote quote) s)))) (quote (lambda (s) (display (list s (list (quote quote) s))))))
Give a code snippet in #Scheme A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program ...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Common_Lisp
Common Lisp
(defstruct huffman-node (weight 0 :type number) (element nil :type t) (encoding nil :type (or null bit-vector)) (left nil :type (or null huffman-node)) (right nil :type (or null huffman-node)))   (defun initial-huffman-nodes (sequence &key (test 'eql)) (let* ((length (length sequence)) (increment (...
Give a code snippet in #Common_Lisp Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Pyret
Pyret
  data Door: | open | closed end   fun flip-door(d :: Door) -> Door: cases(Door) d: | open => closed | closed => open end end     fun flip-doors(doors :: List<Door>) -> List<Door>: doc:```Given a list of door positions, repeatedly switch the positions of every nth door for every nth pass, and re...
Give a code snippet in #Pyret There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, .....
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#C.2B.2B
C++
  #include <math.h> #include <iostream>   unsigned pwr[10];   unsigned munch( unsigned i ) { unsigned sum = 0; while( i ) { sum += pwr[(i % 10)]; i /= 10; } return sum; }   int main( int argc, char* argv[] ) { for( int i = 0; i < 10; i++ ) pwr[i] = (unsigned)pow( (float)i, (f...
Give a code snippet in #C.2B.2B A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see...
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 ...
#Action.21
Action!
BYTE lastError   PROC MyError(BYTE errCode) lastError=errCode RETURN   BYTE FUNC FileExists(CHAR ARRAY fname) DEFINE PTR="CARD" PTR old BYTE dev=[1]   lastError=0 old=Error Error=MyError ;replace error handling to capture I/O error   Close(dev) Open(dev,fname,4) Close(dev)   Error=old ;restore the...
Give a code snippet in #Action.21 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#RLaB
RLaB
>> m = rand(3,5) 0.41844289 0.476591435 0.75054022 0.226388925 0.963880314 0.91267171 0.941762397 0.464227895 0.693482786 0.203839405 0.261512966 0.157981873 0.26582235 0.11557427 0.0442493069 >> m' 0.41844289 0.91267171 0.261512966 0.476591435 0.941762397 0.157981873 0.750...
Give a code snippet in #RLaB Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Lingo
Lingo
on reverse (str) res = "" repeat with i = str.length down to 1 put str.char[i] after res end repeat return res end
Give a code snippet in #Lingo Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#AutoHotkey
AutoHotkey
Sentence := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" Msgbox, % SentenceType(Sentence)   SentenceType(Sentence) { Sentence := Trim(Sentence) Loop, Parse, Sentence, .?! { N := (!E && !Q && !S) ...
Give a code snippet in #AutoHotkey Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its ...
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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.util.List   placesList = [String - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - ] lists = [ - placesList - ,...
Give a code snippet in #NetRexx 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Dyalect
Dyalect
let array = [[2, 12, 10, 4], [18, 11, 20, 2]]   for row in array { break when { for element in row { print("\(element)") if element == 20 { break true } } } } print("*Done")
Give a code snippet in #Dyalect Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#C.2B.2B
C++
#include <cassert> #include <iomanip> #include <iostream> #include <vector>   class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) ...
Give a code snippet in #C.2B.2B The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts t...
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Clojure
Clojure
(require '[clojure.java.jdbc :as sql]) ; Using h2database for this simple example. (def db {:classname "org.h2.Driver"  :subprotocol "h2:file"  :subname "db/my-dbname"})   (sql/db-do-commands db (sql/create-table-ddl :address [:id "bigint primary key auto_increment"] [:street "varchar"] [:...
Give a code snippet in #Clojure Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#AWK
AWK
$ awk '{printf("%d 0%o 0x%x\n",$1,$1,$1)}' 10 10 012 0xa 16 16 020 0x10 255 255 0377 0xff
Give a code snippet in #AWK Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routi...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#HTML
HTML
\b backspace \d delete \e escape \f formfeed \l linefeed \n newline \r return \t horizontal tab \v vertical tab \' single quote \" double quote \\ backslash \ddd octal code \xdd hexadecimal code \^c control code
Give a code snippet in #HTML Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each ot...
#Prolog
Prolog
sexy_prime_group(1, N, _, [N]):- is_prime(N), !. sexy_prime_group(Size, N, Limit, [N|Group]):- is_prime(N), N1 is N + 6, N1 =< Limit, S1 is Size - 1, sexy_prime_group(S1, N1, Limit, Group).   print_sexy_prime_groups(Size, Limit):- findall(G, (is_prime(P), P =< Limit, sexy_prime_group(Siz...
Give a code snippet in #Prolog This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime ...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#FBSL
FBSL
#APPTYPE CONSOLE   PRINT HEX(CHECKSUM("The quick brown fox jumps over the lazy dog"))   PAUSE
Give a code snippet in #FBSL Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#Elixir
Elixir
defmodule Mersenne do def mersenne_factor(p) do limit = :math.sqrt(:math.pow(2, p) - 1) mersenne_loop(p, limit, 1) end   defp mersenne_loop(p, limit, k) when (2*k*p - 1) > limit, do: nil defp mersenne_loop(p, limit, k) do q = 2*k*p + 1 if prime?(q) and rem(q,8) in [1,7] and trial_factor(2,p,q), ...
Give a code snippet in #Elixir A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before ...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Printer
Colour pinstripe/Printer
The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence...
#Raku
Raku
unit sub MAIN ($dpi = 300, $size = 'letter');   my $filename = './Color-pinstripe-printer-perl6.png';   my %paper = ( 'letter' => { :width(8.5), :height(11.0) } 'A4' => { :width(8.2677), :height(11.6929)} );   my ($w, $h) = %paper{$size}<width height> »*» $dpi;   # ROYGBIVK my @color = (1,0,0),(1,.598,0)...
Give a code snippet in #Raku The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included...
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...
#11l
11l
V items = [‘fee fie’, ‘huff and puff’, ‘mirror mirror’, ‘tick tock’]   L L(item) items print(‘#2. #.’.format(L.index + 1, item))   V reply = input(‘Which is from the three pigs: ’).trim(‘ ’) I !reply.is_digit() L.continue   I Int(reply) C 1..items.len print(‘You chose: ’items[Int(reply) - ...
Give a code snippet in #11l 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Forth
Forth
: merge-step ( right mid left -- right mid+ left+ ) over @ over @ < if over @ >r 2dup - over dup cell+ rot move r> over ! >r cell+ 2dup = if rdrop dup else r> then then cell+ ; : merge ( right mid left -- right left ) dup >r begin 2dup > while merge-step repeat 2drop r> ;   : mid ( l r -- mid ) ov...
Give a code snippet in #Forth 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) printCalendar(\A[1]|1969) end   procedure printCalendar(year) #: Print a 3 column x 80 char calendar cols := 3 # fixed width mons := [] # table of months "January February March April May June " || ...
Give a code snippet in #Icon_and_Unicon Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Scheme
Scheme
; linear congruential generator given in C99 section 7.20.2.1 (define ((c-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) (quotient seed 65536))   ; uniform real numbers in open interval (0, 1) (define (unif-rand seed) (let ((r (c-rand seed))) (lambda () (/ (+ (r) 1) 32769.0))))   ; Box-Mul...
Give a code snippet in #Scheme Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Relate...
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: ...
#Run_BASIC
Run BASIC
y = 1 while t <= 10 k1 = t * sqr(y) k2 = (t + .05) * sqr(y + .05 * k1) k3 = (t + .05) * sqr(y + .05 * k2) k4 = (t + .1) * sqr(y + .1 * k3)   if right$(using("##.#",t),1) = "0" then print "y(";using("##",t);") ="; using("####.#######", y);chr$(9);"Error ="; (((t^2 + 4)^2) /16) -y y = y + .1 *(...
Give a code snippet in #Run_BASIC 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} Thi...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub cocktail_sort { my @a = @_; while (1) { my $swapped_forward = 0; for my $i (0..$#a-1) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1; } } last...
Give a code snippet in #Perl 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/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Bracmat
Bracmat
( (fs=/('(x./('(y.map'($x.$y)))))) & (f1=/('(x.$x*2))) & (f2=/('(x.$x^2))) & (partial=/('(x./('(y.($x)$($y)))))) & (!partial$!fs)$!f1:?fsf1 & (!partial$!fs)$!f2:?fsf2 & out$(!fsf1$(0 1 2 3)) & out$(!fsf2$(0 1 2 3)) & out$(!fsf1$(2 4 6 8)) & out$(!fsf2$(2 4 6 8)) );
Give a code snippet in #Bracmat Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nemerle
Nemerle
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   bval = [1, 0, 5, 'a', 1 == 1, 1 \= 1, isTrue, isFalse]   loop b_ = 0 for bval.length select case bval[b_] when isTrue then say bval[b_] 'is true' when isFalse then say bval[b_] 'is false' otherwise say bval[b_]...
Give a code snippet in #Nemerle Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Ada
Ada
generic type Swap_Type is private; -- Generic parameter procedure Generic_Swap (Left, Right : in out Swap_Type);   procedure Generic_Swap (Left, Right : in out Swap_Type) is Temp : constant Swap_Type := Left; begin Left := Right; Right := Temp; end Generic_Swap;
Give a code snippet in #Ada Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity....
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Octave
Octave
function r = isnum(a) if ( isnumeric(a) ) r = 1; else r = ~isnan(str2double(a)); endif endfunction   % tests disp(isnum(123)) % 1 disp(isnum("123")) % 1 disp(isnum("foo123")) % 0 disp(isnum("123bar")) % 0 disp(isnum("3.1415")) % 1
Give a code snippet in #Octave Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Clojure
Clojure
(ns rosettacode.dinesman (:use [clojure.core.logic] [clojure.tools.macro :as macro]))   ; whether x is immediately above (left of) y in list s; uses pattern matching on s (defne aboveo [x y s] ([_ _ (x y . ?rest)]) ([_ _ [_ . ?rest]] (aboveo x y ?rest)))   ; whether x is on a higher floor than y...
Give a code snippet in #Clojure Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#AWK
AWK
$ awk 'BEGIN{print ENVIRON["HOST"]}' E51A08ZD
Give a code snippet in #AWK Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Ruby
Ruby
def sum(var, lo, hi, term, context) sum = 0.0 lo.upto(hi) do |n| sum += eval "#{var} = #{n}; #{term}", context end sum end p sum "i", 1, 100, "1.0 / i", binding # => 5.18737751763962
Give a code snippet in #Ruby Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGO...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#PicoLisp
PicoLisp
(de **Mod (X Y N) (let M 1 (loop (when (bit? 1 Y) (setq M (% (* M X) N)) ) (T (=0 (setq Y (>> 1 Y))) M ) (setq X (% (* X X) N)) ) ) )
Give a code snippet in #PicoLisp Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 23513993033...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#PowerShell
PowerShell
  function entropy ($string) { $n = $string.Length $string.ToCharArray() | group | foreach{ $p = $_.Count/$n $i = [Math]::Log($p,2) -$p*$i } | measure -Sum | foreach Sum } entropy "1223334444"  
Give a code snippet in #PowerShell Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for bina...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Julia
Julia
using Printf   luhntest(x) = luhntest(parse(Int, x))   function checkISIN(inum::AbstractString) if length(inum) != 12 || !all(isalpha, inum[1:2]) return false end return parse.(Int, collect(inum), 36) |> join |> luhntest end   for inum in ["US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU...
Give a code snippet in #Julia An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[ZumkellerQ] ZumkellerQ[n_] := Module[{d = Divisors[n], t, ds, x}, ds = Total[d]; If[Mod[ds, 2] == 1, False , t = CoefficientList[Product[1 + x^i, {i, d}], x]; t[[1 + ds/2]] > 0 ] ]; i = 1; res = {}; While[Length[res] < 220, r = ZumkellerQ[i]; If[r, AppendTo[res, i]]; i++; ]...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no re...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#TXR
TXR
@(bind (width height) (15 15)) @(do (defvar *r* (make-random-state nil)) (defvar vi) (defvar pa)   (defun neigh (loc) (let ((x (from loc)) (y (to loc))) (list (- x 1)..y (+ x 1)..y x..(- y 1) x..(+ y 1))))   (defun make-maze-rec (cu) (set [vi cu] t) (each ((n...
Give a code snippet in #TXR This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#PicoLisp
PicoLisp
(load "@lib/rsa.l") # Use the 'prime?' function from RSA package   (de truncatablePrime? (N Fun) (for (L (chop N) L (Fun L)) (T (= "0" (car L))) (NIL (prime? (format L))) T ) )   (let (Left 1000000 Right 1000000) (until (truncatablePrime? (dec 'Left) cdr)) (until (truncatablePrime? (dec 'Ri...
Give a code snippet in #PicoLisp A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-trunca...
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...
#K
K
ssr: +/1%_sqr ssr 1+!1000 1.643935
Give a code snippet in #K 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#Julia
Julia
  function compress7(inio, outio) nextwritebyte = read(inio, UInt8) & 0x7f filled = 7 while !eof(inio) inbyte = read(inio, UInt8) write(outio, UInt8(nextwritebyte | inbyte << filled)) nextwritebyte = inbyte >> (8 - filled) filled = (filled + 7) % 8 if filled == 0 ...
Give a code snippet in #Julia The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the o...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Factor
Factor
USING: fry kernel lists lists.lazy math math.functions prettyprint ; IN: rosetta-code.generator-exponential   : mth-powers-generator ( m -- lazy-list ) [ 0 lfrom ] dip [ ^ ] curry lmap-lazy ;   : lmember? ( elt list -- ? ) over '[ unswons dup _ >= ] [ drop ] until nip = ;   : 2-not-3-generator ( -- lazy-list ) ...
Give a code snippet in #Factor A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION multiply RETURNS DEC (a AS DEC , b AS DEC ): RETURN a * b . END.
Give a code snippet in #OpenEdge.2FProgress A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as no...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Racket
Racket
#lang racket/base (require plot racket/math)   ;; x and y bounds set to centralise the circle (define (archemedian-spiral-renderer2d a b θ/τ-max #:samples (samples (line-samples))) (define (f θ) (+ a (* b θ))) (define max-dim (+ a (* θ/τ-max 2 pi b))) (polar f ...
Give a code snippet in #Racket The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Collections; using Nemerle.Collections.NCollectionsExtensions;   module AssocArray { Main() : void { def list1 = ["apples", "oranges", "bananas", "kumquats"]; def list2 = [13, 34, 12]; def inventory = Hashtable(ZipLazy(list1, list2)); ...
Give a code snippet in #Nemerle Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Maple
Maple
isperfect := proc(n) return evalb(NumberTheory:-SumOfDivisors(n) = 2*n); end proc: isperfect(6); true
Give a code snippet in #Maple Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Scala
Scala
import scala.math.BigInt   val a = BigInt( "2988348162058574136915891421498819466320163312926952423791023078876139") val b = BigInt( "2351399303373464486466122544523690094744975233415544072992656881240319")   println(a.modPow(b, BigInt(10).pow(40)))
Give a code snippet in #Scala Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 23513993033734...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Kotlin
Kotlin
// Version 1.2.40   fun countJewels(s: String, j: String) = s.count { it in j }   fun main(args: Array<String>) { println(countJewels("aAAbbbb", "aA")) println(countJewels("ZZ", "z")) }
Give a code snippet in #Kotlin Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower cas...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO;   with Ada.Containers.Generic_Array_Sort;   procedure Demo_Array_Sort is   function "+" (S : String) return Unbounded_String renames To_Unbounded_String;   type A_Composite is record Name  : Unbounde...
Give a code snippet in #Ada 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