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/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#ALGOL_68
ALGOL 68
main:( INT two=2, thirty=30; # test constants # PROC VOID undefined;   # First implement exponentiation using a rather slow but sure FOR loop # PROC int pow = (INT base, exponent)INT: ( # PROC cannot be over loaded # IF exponent<0 THEN undefined FI; INT out:=( exponent=0 | 1 | base ); FROM 2 TO expone...
Give a code snippet in #ALGOL_68 Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#PARI.2FGP
PARI/GP
  \\ Tokenize a string str according to 1 character delimiter d. Return a list of tokens. \\ Using ssubstr() from http://rosettacode.org/wiki/Substring#PARI.2FGP \\ tokenize() 3/5/16 aev tokenize(str,d)={ my(str=Str(str,d),vt=Vecsmall(str),d1=sasc(d),Lr=List(),sn=#str,v1,p1=1); for(i=p1,sn, v1=vt[i]; if(v1==d1, listput...
Give a code snippet in #PARI.2FGP Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other task...
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...
#PowerShell
PowerShell
for ($i = 10; $i -ge 0; $i--) { $i }
Give a code snippet in #PowerShell 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/I...
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 ...
#HicEst
HicEst
sum = 0 DO i = 1, 10 sum = sum + i^2 ENDDO WRITE(ClipBoard) "RMS(1..10) = ", (sum/10)^0.5
Give a code snippet in #HicEst 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/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Brainf.2A.2A.2A
Brainf***
++++++++++>>>+[[->>+<[+>->+<<--------------------------------------- -------------------[>>-<++++++++++<[+>-<]]>[-<+>]<++++++++++++++++++ ++++++++++++++++++++++++++++++>]<[<]>>[-<+++++++++++++++++++++++++++ ++++++++++++++++++++++>]>]>[>>>]<<<[.<<<]<.>>>+]
Give a code snippet in #Brainf.2A.2A.2A Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implemen...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#C.2B.2B
C++
#include <iostream> /* Interface for all Continued Fractions Nigel Galloway, February 9th., 2013. */ class ContinuedFraction { public: virtual const int nextTerm(){}; virtual const bool moreTerms(){}; }; /* Create a continued fraction from a rational number Nigel Galloway, February 9th., 2013. */ class r2cf : ...
Give a code snippet in #C.2B.2B Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r ...
christopher/rosetta-code
http://rosettacode.org/wiki/Spinning_rod_animation/Text
Spinning rod animation/Text
Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be...
#ALGOL_68
ALGOL 68
FOR i TO 1 000 DO # increase/decrease the TO value for a longer/shorter animation # FOR d TO 2 000 000 DO SKIP OD; # adjust to change the spin rate # print( ( CASE 1 + i MOD 4 IN "/", "-", "\", "|" ESAC, REPR 8 ) ) OD
Give a code snippet in #ALGOL_68 Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with t...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Python
Python
from __future__ import print_function   def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init positi...
Give a code snippet in #Python One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machin...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Ela
Ela
open list   dotp a b | length a == length b = sum (zipWith (*) a b) | else = fail "Vector sizes must match."   dotp [1,3,-5] [4,-2,-1]
Give a code snippet in #Ela Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] ...
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) ...
#Forth
Forth
include lib/choose.4th ( n1 -- n2) include lib/ctos.4th ( n -- a 1)   10 constant /[] \ maximum number of brackets /[] string [] \ string with brackets \ create string with brackets : make[] ...
Give a code snippet in #Forth 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-n...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#Fortran
Fortran
module lcgs implicit none   integer, parameter :: i64 = selected_int_kind(18) integer, parameter :: a1 = 1103515245, a2 = 214013 integer, parameter :: c1 = 12345, c2 = 2531011 integer, parameter :: div = 65536 integer(i64), parameter :: m = 2147483648_i64 ! need to go to 64 bits because ...
Give a code snippet in #Fortran The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle...
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: ...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П7 1 0 0 * П8 1 ВП 5 / П9 ИП7 1 0 6 7 / П0 5 0 0 * ПC 3 * ПA 1 6 * ПB С/П ПB 1 6 / ПA 3 / ПC 5 0 0 / П0 1 0 6 7 / БП 00
Give a code snippet in #.D0.9C.D0.9A-61.2F52 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, a...
christopher/rosetta-code
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#PowerShell
PowerShell
  function Measure-Apollonius { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [int]$Counter, [double]$x1, [double]$y1, [double]$r1, [double]$x2, [double]$y2, [double]$r2, [double]$x3, [double]$y3, [double]$r3 ...
Give a code snippet in #PowerShell Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty strai...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Yorick
Yorick
#include "button.i"   window, 0; btn_click = Button(text="click me", x=.395, y=.65, dx=0.04368, dy=0.0091); btn_quit = Button(text="quit", x=.395, y=.6, dx=0.02184, dy=0.0091); count = 0; msg = "There have been no clicks yet"; finished = 0; do { fma; plt, msg, .395, .7, justify="CH"; button_plot, btn_click;...
Give a code snippet in #Yorick Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Raku
Raku
my $x; say $x.WHERE;   my $y := $x; # alias say $y.WHERE; # same address as $x   say "Same variable" if $y =:= $x; $x = 42; say $y; # 42  
Give a code snippet in #Raku 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/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 ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import( "fmt" "math" )   var powers [10]int   func isMunchausen(n int) bool { if n < 0 { return false } n64 := int64(n) nn := n64 var sum int64 = 0 for nn > 0 { sum += int64(powers[nn % 10]) if sum > n64 { return false } nn /= 10 } return sum =...
Give a code snippet in #F.C5.8Drmul.C3.A6 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Icon_and_Unicon
Icon and Unicon
procedure main() L := [1, 2r10, 3r10, 4r10, 5r10, 6r10, 7r10, 8r10, 9r10, 10r10, 11r10, 12r10, 13r10, 14r10, 15r10, 16r10, 17r10, 18r10,19r10, 20r10, 21r10, 22r10, 23r10, 24r10, 25r10, 26r10, 27r10, 28r10, 29r10, 30r10, 31r10, 32r10, 33r10, 34r10, 35r10, 36r10]   every write(!L) end
Give a code snippet in #Icon_and_Unicon Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but...
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
#J
J
val=. 0
Give a code snippet in #J 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/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...
#Janet
Janet
  (defn factorial [x] (cond (< x 0) nil (= x 0) 1 (* x (factorial (dec x)))))  
Give a code snippet in #Janet 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 n...
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...
#E
E
def foo(var x) { return fn y { x += y } }
Give a code snippet in #E 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#Ruby
Ruby
N = 2 base = 10 c1 = 0 c2 = 0   for k in 1 .. (base ** N) - 1 c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 print "%d " % [k] end end   puts print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
Give a code snippet in #Ruby Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or other...
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#C.2B.2B
C++
using namespace std;   #include <iostream> #include <ctime>   #define n 100 #define nn ((n * (n + 1)) >> 1)   bool Contains(int lst[], int item, int size) { for (int i = 0; i < size; i++) if (item == lst[i]) return true; return false; }   int * MianChowla() { static int mc[n]; mc[0] = 1; int sums[nn]; sums[0] = 2; ...
Give a code snippet in #C.2B.2B The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairw...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Klong
Klong
  fib::{:[x<0;"error: negative":|x<2;x;.f(x-1)+.f(x-2)]}  
Give a code snippet in #Klong While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwant...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
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 |...
#Lua
Lua
function compare(a, b) print(("%s is of type %s and %s is of type %s"):format( a, type(a), b, type(b) )) if a < b then print(('%s is strictly less than %s'):format(a, b)) end if a <= b then print(('%s is less than or equal to %s'):format(a, b)) end if a > b then print(('%s is stric...
Give a code snippet in #Lua 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 Co...
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...
#jq
jq
jq -rR base64d
Give a code snippet in #jq 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Julia
Julia
  using Sockets   const portnum = 12345   function canopen() try server = listen(portnum) println("This is the only instance.") sleep(20) catch y if findfirst("EADDRINUSE", string(y)) != nothing println("There is already an instance running.") end end end ...
Give a code snippet in #Julia This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Dart
Dart
/* Import math library to get: * 1) Square root function  : Math.sqrt(x) * 2) Power function : Math.pow(base, exponent) * 3) Random number generator : Math.Random() */ import 'dart:math' as Math show sqrt, pow, Random;   // Returns average/mean of a list of numbers num mean(List<num> l) => l.redu...
Give a code snippet in #Dart Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#PureBasic
PureBasic
DataSection puzzle: Data.s "394002670" Data.s "000300400" Data.s "500690020" Data.s "045000900" Data.s "600000007" Data.s "007000580" Data.s "010067008" Data.s "009008000" Data.s "026400735" EndDataSection   #IsPossible = 0 #IsNotPossible = 1 #Unknown = 0 Global Dim sudoku(8, 8) ;-declarations Decl...
Give a code snippet in #PureBasic Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#MiniScript
MiniScript
// flush the keyboard while key.available key.get end while   // and now prompt and wait for Y or N print "Press Y or N:" k = "" while k != "Y" and k != "N" k = key.get.upper end while print "You pressed: " + k
Give a code snippet in #MiniScript Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#zkl
zkl
fcn juliaSet{ w,h,zoom:=800,600, 1; bitmap:=PPM(w,h,0xFF|FF|FF); // White background   cX,cY:=-0.7, 0.27015; moveX,moveY:=0.0, 0.0; maxIter:=255;   foreach x,y in (w,h){ zx:=1.5*(x - w/2)/(0.5*zoom*w) + moveX; zy:=1.0*(y - h/2)/(0.5*zoom*h) + moveY; i:=maxIter; while(zx*zx + z...
Give a code snippet in #zkl Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#E
E
def lookAndSayNext(number :int) { var seen := null var count := 0 var result := "" def put() { if (seen != null) { result += count.toString(10) + E.toString(seen) } } for ch in number.toString(10) { if (ch != seen) { put() seen := ch count := 0 } count += 1 } ...
Give a code snippet in #E The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Lua
Lua
repeat k = math.random(19) print(k) if k == 10 then break end print(math.random(19) until false
Give a code snippet in #Lua Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#AppleScript
AppleScript
script Animal end script   script Dog property parent : Animal end script   script Cat property parent : Animal end script   script Lab property parent : Dog end script   script Collie property parent : Dog end script
Give a code snippet in #AppleScript This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Perl
Perl
#!/usr/bin/perl -w use strict; use X11::Protocol;   my $X = X11::Protocol->new;   my $window = $X->new_rsrc; $X->CreateWindow ($window, $X->root, # parent window 'InputOutput', # class 0, # depth, copy from parent 0, ...
Give a code snippet in #Perl Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Maple
Maple
convertDiscordian := proc(year, month, day) local days31, days30, daysThisYear, i, dYear, dMonth, dDay, seasons, week, dayOfWeek; days31 := [1, 3, 5, 7, 8, 10, 12]; days30 := [4, 6, 9, 11]; if month < 1 or month >12 then error "Invalid month: %1", month; end if; if (member(month, days31) and day > 31) or (membe...
Give a code snippet in #Maple Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Vlang
Vlang
fn main() { println(mode([2, 7, 1, 8, 2])) println(mode([2, 7, 1, 8, 2, 8])) }   fn mode(a []int) []int { mut m := map[int]int{} for v in a { m[v]++ } mut mode := []int{} mut n := 0 for k, v in m { match true { v > n { n = v mod...
Give a code snippet in #Vlang Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if po...
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      ...
#Maxima
Maxima
/* Using ?format from the unerlying Lisp system */   lambda([],block([q:ascii(34),s:"lambda([],block([q:ascii(34),s:~A~A~A],print(?format(false,s,q,s,q))))()$"],print(?format(false,s,q,s,q))))()$
Give a code snippet in #Maxima 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/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#Go
Go
package cf   import ( "fmt" "strings" )   // ContinuedFraction is a regular continued fraction. type ContinuedFraction func() NextFn   // NextFn is a function/closure that can return // a posibly infinite sequence of values. type NextFn func() (term int64, ok bool)   // String implements fmt.Stringer. // It formats a...
Give a code snippet in #Go Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Arturo
Arturo
print {: The “Red Death” had long devastated the country. No pestilence had ever been so fatal, or so hideous.   Blood was its Avator and its seal— the redness and the horror of blood.   There were sharp pains, and sudden dizziness, and then profuse bleeding at the pores...
Give a code snippet in #Arturo A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) follow...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"]; Print[ReadString[str, EndOfFile]]; Close[str], str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]]; WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]]; Close[str]]
Give a code snippet in #Mathematica.2FWolfram_Language Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are append...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#NewLISP
NewLISP
;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html ;; (import native functions from the crypto library, provided by OpenSSL) (module "crypto.lsp") (crypto:sha256 "Rosetta Code")
Give a code snippet in #NewLISP SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Mythryl
Mythryl
print "Hello world!";
Give a code snippet in #Mythryl Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Forth
Forth
  wordlist constant dict   : load-dict ( c-addr u -- ) r/o open-file throw >r begin pad 1024 r@ read-line throw while pad swap ['] create execute-parsing repeat drop r> close-file throw ;   : xreverse {: c-addr u -- c-addr2 u :} u allocate throw u + c-addr swap over u + >r begin ( from to r:en...
Give a code snippet in #Forth A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the tota...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Ring
Ring
  for i = 1 to 5 for x = 1 to i see "*" next see nl next  
Give a code snippet in #Ring “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structur...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Wren
Wren
import "/rat" for Rat import "/fmt" for Fmt   var tests = [0.9054054, 0.518518, 0.75] for (test in tests) { var r = Rat.fromFloat(test) System.print("%(Fmt.s(-9, test)) -> %(r)") }
Give a code snippet in #Wren This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is ...
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) ...
#C
C
#include<stdio.h> #include<stdlib.h> #include<string.h>   int isBal(const char*s,int l){ signed c=0; while(l--) if(s[l]==']') ++c; else if(s[l]=='[') if(--c<0) break; return !c; }   void shuffle(char*s,int h){ int x,t,i=h; while(i--){ t=s[x=rand()%h]; s[x]=s[i]; s[i]=t; } }   void genSeq(ch...
Give a code snippet in #C 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....
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...
#Lua
Lua
local N = 1000035   -- FUNCS: local function T(t) return setmetatable(t, {__index=table}) end table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end table.lastn = fun...
Give a code snippet in #Lua 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 num...
christopher/rosetta-code
http://rosettacode.org/wiki/Graph_colouring
Graph colouring
A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges define the nodes being connected...
#Python
Python
import re from collections import defaultdict from itertools import count     connection_re = r""" (?: (?P<N1>\d+) - (?P<N2>\d+) | (?P<N>\d+) (?!\s*-)) """   class Graph:   def __init__(self, name, connections): self.name = name self.connections = connections g = self.graph = default...
Give a code snippet in #Python A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#GML
GML
draw_point(100, 100);
Give a code snippet in #GML Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   ReadOnly table = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, ...
Give a code snippet in #Visual_Basic_.NET The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Erlang
Erlang
-module(map_range). -export([map_value/3]).   map_value({A1,A2},{B1,B2},S) -> B1 + (S - A1) * (B2 - B1) / (A2 - A1).  
Give a code snippet in #Erlang Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#ACL2
ACL2
(defun fac (n) (if (zp n) 1 (* n (fac (1- n)))))   (defconst *pi-approx* (/ 3141592653589793238462643383279 (expt 10 30)))   (include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)   (defun dgt-to-str (d) (case d (1 "1") (2 "2") (3 "3") (4 "4") (5 "5") (6 "6") (7 "7...
Give a code snippet in #ACL2 Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evalua...
christopher/rosetta-code
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
edges = {1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5, 3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7}; t = TreeGraph[edges, GraphStyle -> "VintageDiagram"]
Give a code snippet in #Mathematica.2FWolfram_Language A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   ne...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial long division is an algorithm for d...
#Haskell
Haskell
import Data.List   shift n l = l ++ replicate n 0   pad n l = replicate n 0 ++ l   norm :: Fractional a => [a] -> [a] norm = dropWhile (== 0)   deg l = length (norm l) - 1   zipWith' op p q = zipWith op (pad (-d) p) (pad d q) where d = (length p) - (length q)   polydiv f g = aux (norm f) (norm g) [] where aux f s q...
Give a code snippet in #Haskell This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Vlang
Vlang
import time   fn main() { println(time.now().custom_format("YYYY-MM-DD")) println(time.now().custom_format("dddd, MMMM D, YYYY")) }
Give a code snippet in #Vlang This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Objeck
Objeck
use Collection;   class Proper{ function : Main(args : String[]) ~ Nil { for(x := 1; x <= 10; x++;) { Print(x, ProperDivs(x)); };   x := 0; count := 0;   for(n := 1; n <= 20000; n++;) { if(ProperDivs(n)->Size() > count) { x := n; count := ProperDivs(n)->Size(); };...
Give a code snippet in #Objeck The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divi...
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...
#Pascal
Pascal
print substr("knight",1), "\n"; # strip first character print substr("socks", 0, -1), "\n"; # strip last character print substr("brooms", 1, -1), "\n"; # strip both first and last characters
Give a code snippet in #Pascal 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/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...
#Elixir
Elixir
iex(1)> code = ?a 97 iex(2)> to_string([code]) "a"
Give a code snippet in #Elixir 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). Con...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ [ 1 1 30 times [ tuck + ] swap join ] constant do ] is phi ( --> n/d )   [ 2dup 5 1 v< iff 2drop done 2dup 5 1 v/ proper 2drop wide 2dup walk 1 5 turn 2dup phi v/ 2dup recurse -2 5 turn recurse 1 5 turn -v fl...
Give a code snippet in #Quackery Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#BQN
BQN
AGM ← { (|𝕨-𝕩) ≤ 1e¯15? 𝕨; (0.5×𝕨+𝕩) 𝕊 √𝕨×𝕩 }   1 AGM 1÷√2
Give a code snippet in #BQN This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#AppleScript
AppleScript
on juggler(n) script o property sequence : {n} end script   set i to 1 set {max, pos} to {n, i} repeat until (n = 1) set n to n ^ (n mod 2 + 0.5) div 1 set end of o's sequence to n set i to i + 1 if (n > max) then set {max, pos} to {n, i} end repeat   ...
Give a code snippet in #AppleScript Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls ...
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...
#J
J
  echo 'Use: ' , (;:inv 2 {. ARGV) , ' <reference value> <observations>'   data=: ([: ". [: ;:inv 2&}.) ::([: exit 1:) ARGV   ([: exit (1: echo@('insufficient data'"_)))^:(2 > #) data   mean=: +/ % # variance=: [: mean [: *: -   averageError=: ({. variance }.)@:] crowdError=: variance {. diversity=: variance }.   ec...
Give a code snippet in #J 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/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...
#BCPL
BCPL
get "libhdr"   let start() be for p=2 to 6 by 2 for s=1 to 7 for f=1 to 7 if p~=s & s~=f & p~=f & p+s+f=12 then writef("%N %N %N*N", p, s, f)
Give a code snippet in #BCPL 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/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#BCPL
BCPL
get "libhdr"   let toroman(n, v) = valof $( let extract(n, val, rmn, v) = valof $( while n >= val $( n := n - val; for i=1 to rmn%0 do v%(v%0+i) := rmn%i v%0 := v%0 + rmn%0 $) resultis n $)   v%0 := 0 n := extract(n, 1000, "M", v) n := extract(n, ...
Give a code snippet in #BCPL Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a valu...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#PHP
PHP
max($values)
Give a code snippet in #PHP Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Python
Python
import math def yinyang(n=3): radii = [i * n for i in (1, 3, 6)] ranges = [list(range(-r, r+1)) for r in radii] squares = [[ (x,y) for x in rnge for y in rnge] for rnge in ranges] circles = [[ (x,y) for x,y in sqrpoints if math.hypot(x,y) <= radius ] for sqrpoints, radius in zip(squares, radii)]...
Give a code snippet in #Python One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#F.23
F#
let rec agm a g precision = if precision > abs(a - g) then a else agm (0.5 * (a + g)) (sqrt (a * g)) precision   printfn "%g" (agm 1. (sqrt(0.5)) 1e-15)
Give a code snippet in #F.23 This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Ada
Ada
type Pixel_Count is mod 2**64; type Histogram is array (Luminance) of Pixel_Count;   function Get_Histogram (Picture : Grayscale_Image) return Histogram is Result : Histogram := (others => 0); begin for I in Picture'Range (1) loop for J in Picture'Range (2) loop declare Count : Pixel_Co...
Give a code snippet in #Ada Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#PARI.2FGP
PARI/GP
permutationSort(v)={ my(u); for(k=1,(#v)!, u=vecextract(v, numtoperm(#v,k)); for(i=2,#u, if(u[i]<u[i-1], next(2)) ); return(u) ) };
Give a code snippet in #PARI.2FGP 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 | Quic...
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.
#Oforth
Oforth
: createVar(varname) "tvar: " varname + eval ;   "myvar" createVar   12 myvar put myvar at .
Give a code snippet in #Oforth 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/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...
#Haskell
Haskell
import Data.Bool (bool) import Data.List (intercalate, unfoldr) import Data.Tuple (swap)   ------------- FAIR SHARE BETWEEN TWO AND MORE ------------   thueMorse :: Int -> [Int] thueMorse base = baseDigitsSumModBase base <$> [0 ..]   baseDigitsSumModBase :: Int -> Int -> Int baseDigitsSumModBase base n = mod ( su...
Give a code snippet in #Haskell 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-out...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
RPGGEN set attr = $lb("")  ; empty list to start write "Rules:",!,"1.) Total of 6 attributes must be at least 75.",!,"2.) At least two scores must be 15 or more.",!    ; loop until valid result do {  ; loop through 6 attributes for i = 1:1:6 { set (low, dice, keep) = ""   ...
Give a code snippet in #Cach.C3.A9_ObjectScript RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#DCL
DCL
$ time = f$time() $ number = f$extract( f$length( time ) - 1, 1, time ) + 1 $ loop: $ inquire guess "enter a guess (integer 1-10) " $ if guess .nes. number then $ goto loop $ write sys$output "Well guessed!"
Give a code snippet in #DCL Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "...
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#PL.2FI
PL/I
smith: procedure options(main); /* find the digit sum of N */ digitSum: procedure(nn) returns(fixed); declare (n, nn, s) fixed; s = 0; do n=nn repeat(n/10) while(n>0); s = s + mod(n,10); end; return(s); end digitSum;   /* find and count factors of N */...
Give a code snippet in #PL.2FI Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Name_Game
The Name Game
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like this: Gary, Gary, bo-bary...
#Picat
Picat
  print_name_game(Name), Name = [V|Rest], membchk(V, ['A', 'E', 'I', 'O', 'U']) => L = to_lowercase(V), Low = [L|Rest], print_verse(Name, [b|Low], [f|Low], [m|Low]).   print_name_game(Name), Name = ['B'|Rest] => print_verse(Name, Rest, [f|Rest], [m|Rest]).   print_name_game(Name), Name = ['F'|Rest] => ...
Give a code snippet in #Picat Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be lik...
christopher/rosetta-code
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#REXX
REXX
/*REXX program performs range consolidation (they can be [equal] ascending/descending). */ #.= /*define the default for range sets. */ parse arg #.1 /*obtain optional arguments from the CL*/ if #.1='' then do ...
Give a code snippet in #REXX Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range ...
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...
#Ruby
Ruby
def mean(a) = a.sum(0.0) / a.size def mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 })   def diversity_theorem(truth, predictions) average = mean(predictions) puts "truth: #{truth}, predictions #{predictions}", "average-error: #{mean_square_diff(truth, predictions)}", ...
Give a code snippet in #Ruby 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#Pop11
Pop11
;;; Initial array lvars ar = {1 2 3 2 3 4}; ;;; Create a hash table lvars ht= newmapping([], 50, 0, true); ;;; Put all array as keys into the hash table lvars i; for i from 1 to length(ar) do 1 -> ht(ar(i)) endfor;   ;;; Collect keys into a list lvars ls = []; appdata(ht, procedure(x); cons(front(x), ls) -> ls; endp...
Give a code snippet in #Pop11 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/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...
#Crystal
Crystal
def subarray_sum(arr) max, slice = 0, [] of Int32 arr.each_index do |i| (i...arr.size).each do |j| sum = arr[i..j].sum max, slice = sum, arr[i..j] if sum > max end end [max, slice] end
Give a code snippet in #Crystal 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 ar...
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 ...
#Pop11
Pop11
if condition then  ;;; Action endif;
Give a code snippet in #Pop11 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#PureBasic
PureBasic
Procedure.s escapeChars(text.s) Static specialChars.s = "[\^$.|?*+()" Protected output.s, nextChar.s, i, countChar = Len(text) For i = 1 To countChar nextChar = Mid(text, i, 1) If FindString(specialChars, nextChar, 1) output + "\" + nextChar Else output + nextChar EndIf Next Proce...
Give a code snippet in #PureBasic A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#PL.2FI
PL/I
  stripper: proc options (main); declare s character (100) varying; declare i fixed binary;   s = 'the quick brown fox jumped'; /* A loop to replace blanks with control characters */ do i = 1 to length(s); if substr(s, i, 1) = ' ' then substr(s, i, 1) = '01'x; end; put skip list (s);...
Give a code snippet in #PL.2FI Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters strippe...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#AutoHotkey
AutoHotkey
ThueMorse(num, iter){ if !iter return num for i, n in StrSplit(num) opp .= !n res := ThueMorse(num . opp, --iter) return res }
Give a code snippet in #AutoHotkey Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 ...
#BBC_BASIC
BBC BASIC
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cit...
Give a code snippet in #BBC_BASIC 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#PowerShell
PowerShell
  $IsOdd = -not ( [bigint]$N ).IsEven $IsEven = ( [bigint]$N ).IsEven  
Give a code snippet in #PowerShell Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#SQL
SQL
CREATE TEMPORARY TABLE inputs(remainder INT, modulus INT);   INSERT INTO inputs VALUES (2, 3), (3, 5), (2, 7);   WITH recursive   -- Multiply out the product of moduli multiplication(idx, product) AS ( SELECT 1, 1   UNION ALL   SELECT multiplication.idx+1, multiplication.product * inputs.mod...
Give a code snippet in #SQL Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#PowerShell
PowerShell
  $path = "C:\Users" if((Dir $path).Count -eq 0) { "$path is empty" } else { "$path is not empty" }  
Give a code snippet in #PowerShell Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#COBOL
COBOL
*>* Ethiopian multiplication   IDENTIFICATION DIVISION. PROGRAM-ID. ethiopian-multiplication. DATA DIVISION. LOCAL-STORAGE SECTION. 01 l PICTURE 9(10) VALUE 17. 01 r PICTURE 9(10) VALUE 34. 01 ethiopian-multiply PICTURE 9(20). ...
Give a code snippet in #COBOL Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and w...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#C
C
#include <stdio.h> #include <stdlib.h>   typedef unsigned long long xint; typedef unsigned uint; typedef struct { uint x, y; // x > y always xint value; } sum_t;   xint *cube; uint n_cubes;   sum_t *pq; uint pq_len, pq_cap;   void add_cube(void) { uint x = n_cubes++; cube = realloc(cube, sizeof(xint) * (n_cubes + 1...
Give a code snippet in #C A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#PureBasic
PureBasic
#MAXNUM = 15 Declare catalan()   If OpenConsole("Catalan numbers") catalan() Input() End 0 Else End -1 EndIf   Procedure catalan() Define k.i, n.i, num.d, den.d, cat.d   Print("1 ")   For n=2 To #MAXNUM num=1 : den =1 For k=2 To n num * (n+k) den * k cat = num / den Next ...
Give a code snippet in #PureBasic Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Oforth
Oforth
: fact(n) n ifZero: [ 1 ] else: [ n n 1- fact * ] ;
Give a code snippet in #Oforth 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#J
J
(1&o. , 2&o. ,: 3&o.) (4 %~ o. 1) , 180 %~ o. 45 0.707107 0.707107 0.707107 0.707107 1 1
Give a code snippet in #J Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate ...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Scala
Scala
def permute(l: List[Double]): List[List[Double]] = l match { case Nil => List(Nil) case x :: xs => for { ys <- permute(xs) position <- 0 to ys.length (left, right) = ys splitAt position } yield left ::: (x :: right) }   def computeAllOperations(l: List[Double]): List[(Double,String)] = l m...
Give a code snippet in #Scala task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Liberty_BASIC
Liberty BASIC
  global pi pi = acs(-1)   Print "Average of:" for i = 1 to 4 read t$ print t$ a=time2angle(t$) ss=ss+sin(a) sc=sc+cos(a) next a=atan2(ss,sc) if a<0 then a=a+2*pi print "is ";angle2time$(a)   end data "23:00:17", "23:40:20", "00:12:45", "00:17:19"   function nn$(n) nn$=right$("0";n, 2) end func...
Give a code snippet in #Liberty_BASIC Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using th...
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 ...
#Nim
Nim
type BitWriter * = tuple file: File bits: uint8 nRemain: int   BitReader * = tuple file: File bits: uint8 nRemain: int nRead: int   proc newBitWriter * (file: File) : ref BitWriter = result = new BitWriter result.file = file result.bits = 0 result.nRemain = 8   proc flushBits (st...
Give a code snippet in #Nim 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 out...
christopher/rosetta-code
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#Ruby
Ruby
#A straight forward implementation of N. Johnston's algorithm. I prefer to look at this as 2n+1 where #the second n is first n reversed, and the 1 is always the second symbol. This algorithm will generate #just the left half of the result by setting l to [1,2] and looping from 3 to 6. For the purpose of #this task I am...
Give a code snippet in #Ruby A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 |...
#360_Assembly
360 Assembly
* Bitwise operations 15/02/2017 BITWISE CSECT USING BITWISE,R13 B 72(R15) DC 17F'0' STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 L R1,A XDECO R1,PG MVC OP,=CL7'A=' ...
Give a code snippet in #360_Assembly 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 Oper...
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: ...
#D
D
import std.stdio, std.math, std.typecons;   alias FP = real; alias FPs = Typedef!(FP[101]);   void runge(in FP function(in FP, in FP) pure nothrow @safe @nogc yp_func, ref FPs t, ref FPs y, in FP dt) pure nothrow @safe @nogc { foreach (immutable n; 0 .. t.length - 1) { immutable FP ...
Give a code snippet in #D 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 equati...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#zonnon
zonnon
  module MatrixOps; type Matrix = array {math} *,* of integer;     procedure WriteMatrix(x: array {math} *,* of integer); var i,j: integer; begin for i := 0 to len(x,0) - 1 do for j := 0 to len(x,1) - 1 do write(x[i,j]); end; writeln; end end WriteMatrix;   procedure Multiplication; var a,b...
Give a code snippet in #zonnon Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#OCaml
OCaml
let map_range (a1, a2) (b1, b2) s = b1 +. ((s -. a1) *. (b2 -. b1) /. (a2 -. a1))   let () = print_endline "Mapping [0,10] to [-1,0] at intervals of 1:"; for i = 0 to 10 do Printf.printf "f(%d) = %g\n" i (map_range (0.0, 10.0) (-1.0, 0.0) (float i)) done
Give a code snippet in #OCaml Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly m...
christopher/rosetta-code