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/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...
#Crystal
Crystal
a, b = b, a
Give a code snippet in #Crystal 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 generic...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window import "math" for Point   class PlotCoordinates { construct new(width, height) { Window.title = "Plot coordinates" Window.resize(width, height) Canvas.resize(width, height) _width = width _height = height...
Give a code snippet in #Wren Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Fortran
Fortran
module pangram   implicit none private public :: is_pangram character (*), parameter :: lower_case = 'abcdefghijklmnopqrstuvwxyz' character (*), parameter :: upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'   contains   function to_lower_case (input) result (output)   implicit none character (*), intent (i...
Give a code snippet in #Fortran Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task W...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( 9 10 3 1 4 5 8 7 6 2 ) sort print
Give a code snippet in #Phixmonti 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/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#AWK
AWK
  # syntax: GAWK -f NIM_GAME.AWK BEGIN { tokens = 12 printf("Nim game - using %d tokens\n",tokens) while (tokens > 0) { for (;;) { printf("how many tokens 1-3? ") getline ans if (ans ~ /^[123]$/) { tokens -= ans prn("player") break } ...
Give a code snippet in #AWK Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#jq
jq
# multiply two decimal strings, which may be signed (+ or -) def long_multiply(num1; num2):   def stripsign: .[0:1] as $a | if $a == "-" then [ -1, .[1:]] elif $a == "+" then [ 1, .[1:]] else [1, .] end;   def adjustsign(sign): if sign == 1 then . else "-" + . end;   # mult/2 ass...
Give a code snippet in #jq Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Liberty_BASIC
Liberty BASIC
  'Liberty BASIC does not support escape characters within literal strings. print "Quotation mark:" print chr$(34) print   'Print literal string print "Hello, World." 'Print literal string displaying quotation marks. print chr$(34) + "Hello, World." + chr$(34)  
Give a code snippet in #Liberty_BASIC Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special chara...
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.)
#LSE
LSE
* Ceci est un commentaire qui prend fin quand la ligne se termine   (* Ceci est un commentaire sur plusieurs lignes comme vous pouvez le voir puisqu'il s'étend sur plusieurs lignes justement... *)   (* Cette exemple est selon la revision LSE-2000 *)
Give a code snippet in #LSE 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/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#MATLAB_.2F_Octave
MATLAB / Octave
function y = rescale(x)   L = [0,.06:.05:1.02]; V = [.1,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.9,.94,.98,1];   y = x; for k=1:numel(x); y(k) = V(sum(L<=x(k))); end; end;   t=0:0.001:1; plot(t,rescale(t));
Give a code snippet in #MATLAB_.2F_Octave A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between  ...
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...
#OCaml
OCaml
let rec factorial n = if n <= 0 then 1 else n * factorial (n-1)
Give a code snippet in #OCaml 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/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Python
Python
from prime_decomposition import decompose from itertools import islice, count try: from functools import reduce except: pass     def almostprime(n, k=2): d = decompose(n) try: terms = [next(d) for i in range(k)] return reduce(int.__mul__, terms, 1) == n except: return False...
Give a code snippet in #Python A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   w...
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
#gecho
gecho
'Hello, <> 'World! print
Give a code snippet in #gecho 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/Stand...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#zig
zig
const std = @import("std"); const fmt = std.fmt; const warn = std.debug.warn;   pub fn main() void { var i: u8 = 0; var buf: [3]u8 = undefined;   while (i < 255) : (i += 1) { _ = fmt.formatIntBuf(buf[0..], i, 8, false, 0); // buffer, value, base, uppercase, width warn("{}\n", buf); } }
Give a code snippet in #zig Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
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 ...
#Maxima
Maxima
load(graphs)$   g: random_tree(10)$   is_tree(g); true   draw_graph(g)$
Give a code snippet in #Maxima 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   hier...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#XPL0
XPL0
func real Dot(W,X,Y,Z); \Return the dot product of two 2D vectors real W,X,Y,Z; \ (W-X) dot (Y-Z) real WX(2), YZ(2); [WX(0):= W(0)-X(0); WX(1):= W(1)-X(1); YZ(0):= Y(0)-Z(0); YZ(1):= Y(1)-Z(1); return WX(0)*YZ(0) + WX(1)*YZ(1); ];   real A,B,C; \triangle   func PointInTr...
Give a code snippet in #XPL0 Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the a...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Ada
Ada
with Ada.Strings.Fixed, Ada.Integer_Text_IO;   procedure Substrings is begin Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "the three truths", Pattern => "th")); Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "ababababab", ...
Give a code snippet in #Ada Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Fizzbuzz is begin for I in 1..100 loop if I mod 15 = 0 then Put_Line("FizzBuzz"); elsif I mod 5 = 0 then Put_Line("Buzz"); elsif I mod 3 = 0 then Put_Line("Fizz"); else Put_Line(Integer'Image(I)); end if;...
Give a code snippet in #Ada Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#360_Assembly
360 Assembly
* Compare a list of strings 31/01/2017 COMPLIST CSECT USING COMPLIST,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) ...
Give a code snippet in #360_Assembly Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_dates
Palindrome dates
Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program which calculates and shows th...
#Sidef
Sidef
var palindates = gather { for y in (2020 .. 9999) { var (m, d) = Str(y).flip.last(4).split(2)... with ([y,m,d].join('-')) {|t| take(t) if Date.valid(t, "%Y-%m-%d") } } }   say "Count of palindromic dates [2020..9999]: #{palindates.len}"   for a,b in ([ ["First 15:", palin...
Give a code snippet in #Sidef Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a progra...
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...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program character.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessCodeChar: .ascii "The code of character is :" sZoneconv: .fill 12,1,' ' szCarriageRet...
Give a code snippet in #ARM_Assembly 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)...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#AppleScript
AppleScript
-- equilibriumIndices :: [Int] -> [Int] on equilibriumIndices(xs)   script balancedPair on |λ|(a, pair, i) set {x, y} to pair if x = y then {i - 1} & a else a end if end |λ| end script   script plus on |λ...
Give a code snippet in #AppleScript An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream(); const assert = std.debug.assert;   pub fn main() !void { const primes = [_]u7{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, ...
Give a code snippet in #Zig Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#SenseTalk
SenseTalk
removeLines "foobar.txt", 1, 2 to handle removeLines fileName, startingLine, linesToRemove If there is no file fileName then put !"No such file: [[the folder & fileName]]" Return End if set endingLine to startingLine + linesToRemove - 1 If endingLine is more than number of lines in file fileName then put !"Ca...
Give a code snippet in #SenseTalk Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to...
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 ...
#Java
Java
import static java.util.Arrays.stream;   public class ChineseRemainderTheorem {   public static int chineseRemainder(int[] n, int[] a) {   int prod = stream(n).reduce(1, (i, j) -> i * j);   int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i...
Give a code snippet in #Java 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 {\displayst...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#GW-BASIC
GW-BASIC
  10 LET I% = 0 20 ' first iteration - before the WHILE 30 LET I% = I% + 1 40 PRINT I% 50 WHILE I% MOD 6 <> 0 60 LET I% = I% + 1 70 PRINT I% 80 WEND  
Give a code snippet in #GW-BASIC Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#Julia
Julia
sqdict(n) = Dict([(x*x, x) for x in 1:n]) numnotsame(arrarr) = sum(map(x -> !all(y -> y == x[1], x), arrarr))   function filtertriangles(N) sqd = sqdict(N) t60 = Vector{Vector{Int}}() t90 = Vector{Vector{Int}}() t120 = Vector{Vector{Int}}() for x in 1:N, y in 1:x xsq, ysq, xy = (x*x, y*y, x*...
Give a code snippet in #Julia The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
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 |...
#Aikido
Aikido
    var portaddr = 0x80 var v = peek (portaddr, 1) // 1 byte v |= 0x40 poke (portaddr, v, 1) // 1 byte back again   var addr = malloc (16) poke (addr, 1234, 4) poke (addr+4, 0, 2) poke (addr+6, 12, 2)    
Give a code snippet in #Aikido Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Ada
Ada
generic type Element is private; with function "=" (E1, E2 : Element) return Boolean is <>; with function "<" (E1, E2 : Element) return Boolean is <>; type Index is (<>); type Arr is array (Index range <>) of Element; procedure Bubble_Sort (A : in out Arr);   procedure Bubble_Sort (A : in out Arr) is Finished : B...
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/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Vorpal
Vorpal
self.a = method(k, x1, x2, x3, x4, x5){ b = method(){ code.k = code.k - 1 return( self.a(code.k, code, code.x1, code.x2, code.x3, code.x4) ) } b.k = k b.x1 = x1 b.x2 = x2 b.x3 = x3 b.x4 = x4 b.x5 = x5   if(k <= 0){ return(self.apply(x4) + self.apply(x5)) } else{ return(self.apply(b...
Give a code snippet in #Vorpal Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The a...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Ada
Ada
with Ada.Text_IO;   procedure Modular_Demo is   type Modul_13 is mod 13;   function F (X : Modul_13) return Modul_13 is begin return X**100 + X + 1; end F;   package Modul_13_IO is new Ada.Text_IO.Modular_IO (Modul_13);   use Ada.Text_IO; use Modul_13_IO; X_Integer  : constant Intege...
Give a code snippet in #Ada Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Scheme
Scheme
(define (dot-product A B) (apply + (map * (vector->list A) (vector->list B))))   (define (cross-product A B) (define len (vector-length A)) (define xp (make-vector (vector-length A) #f)) (let loop ((n 0)) (vector-set! xp n (- (* (vector-ref A (modulo (+ n 1) len)) (vector-ref B (modulo (+ n 2) len))) ...
Give a code snippet in #Scheme A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of n...
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...
#jq
jq
def s(n): reduce range(1; n+1) as $k (0; . + 1/($k * $k) );   s(1000)  
Give a code snippet in #jq Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Lua
Lua
local primegen = { count_limit = 2, value_limit = 3, primelist = { 2, 3 }, nextgenvalue = 5, nextgendelta = 2, tbd = function(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end local limit = math.sqrt(n) for f = 5, limit, 6 do if...
Give a code snippet in #Lua Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or progra...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Stata
Stata
program last_fridays args year clear qui set obs 12 gen day=dofm(mofd(mdy(_n,1,`year'))+1)-1 qui replace day=day-mod(dow(day)-5,7) format %td day list, noobs noheader sep(6) end   last_fridays 2012   +-----------+ | 27jan2012 | | 24feb2012 | | 30mar2012 | | 27apr2012 | | 25may2012 | | 29jun2012 | ...
Give a code snippet in #Stata Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Tcl
Tcl
proc binSrch {lst x} { set len [llength $lst] if {$len == 0} { return -1 } else { set pivotIndex [expr {$len / 2}] set pivotValue [lindex $lst $pivotIndex] if {$pivotValue == $x} { return $pivotIndex } elseif {$pivotValue < $x} { set recursive ...
Give a code snippet in #Tcl A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret num...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
19^^91g5dcg2h6da7260a9f3c4a 2^^11110001001000000
Give a code snippet in #Mathematica.2FWolfram_Language It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Objective-C
Objective-C
NSString *path = [NSString stringWithString:@"/usr/share/dict/words"]; NSError *error = nil; NSString *words = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];  
Give a code snippet in #Objective-C Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
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...
#Java
Java
import java.util.Random;   Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
Give a code snippet in #Java 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. I...
christopher/rosetta-code
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#Lua
Lua
function solve(angle, maxlen, filter) local squares, roots, solutions = {}, {}, {} local cos2 = ({[60]=-1,[90]=0,[120]=1})[angle] for i = 1, maxlen do squares[i], roots[i^2] = i^2, i end for a = 1, maxlen do for b = a, maxlen do local lhs = squares[a] + squares[b] + cos2*a*b local c = roots[lhs]...
Give a code snippet in #Lua The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   th...
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...
#Elixir
Elixir
defmodule Taxicab do def numbers(n \\ 1200) do (for i <- 1..n, j <- i..n, do: {i,j}) |> Enum.group_by(fn {i,j} -> i*i*i + j*j*j end) |> Enum.filter(fn {_,v} -> length(v)>1 end) |> Enum.sort end end   nums = Taxicab.numbers |> Enum.with_index Enum.each(nums, fn {x,i} -> if i in 0..24 or i in 1999.....
Give a code snippet in #Elixir 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 k...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Scala
Scala
  def strings_are_equal(seq:List[String]):Boolean = seq match { case Nil => true case s::Nil => true case el1 :: el2 :: tail => el1==el2 && strings_are_equal(el2::tail) }   def asc_strings(seq:List[String]):Boolean = seq match { case Nil => true case s::Nil => true case el1 :: el2 :: tail => el1...
Give a code snippet in #Scala Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false ...
christopher/rosetta-code
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Raku
Raku
use experimental :pack;   # Joysticks generally show up in the /dev/input/ directory as js(n) where n is # the number assigned by the OS. E.G. /dev/input/js1 . In my particular case:   my $device = '/dev/input/js0';   my $exit = 0;   my $event-stream = $device.IO.open(:bin); my $js = $event-stream.Supply(:8size);   my ...
Give a code snippet in #Raku The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent ...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Julia
Julia
using Printf   function middle3(n::Integer) l = ndigits(n) iseven(l) && error("n must have an odd number of digits") l < 3 && error("n must have 3 digits or more") mid = (l + 1) ÷ 2 abs(n) ÷ 10^(mid-2) % 10^3 end   for n = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12...
Give a code snippet in #Julia Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be te...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#Elena
Elena
import system'routines; import extensions;   public program() { var unsorted := new int[]{6, 2, 7, 8, 3, 1, 10, 5, 4, 9};   console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable()) }
Give a code snippet in #Elena 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/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Ada
Ada
function Get_String return String is Line : String (1 .. 1_000); Last : Natural; begin Get_Line (Line, Last); return Line (1 .. Last); end Get_String;   function Get_Integer return Integer is S : constant String := Get_String; begin return Integer'Value (S); -- may raise exception Constraint_Error if val...
Give a code snippet in #Ada User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and computer science, the Levenshtein ...
#Dyalect
Dyalect
func levenshtein(s, t) { var n = s.Length() var m = t.Length() var d = Array.Empty(n + 1, () => Array.Empty(m + 1))   if n == 0 { return m }   if (m == 0) { return n }   for i in 0..n { d[i][0] = i }   for j in 0..m { d[0][j] = j }   for j ...
Give a code snippet in #Dyalect This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and c...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#Factor
Factor
: list-each ( linked-list quot: ( data -- ) -- ) [ [ data>> ] dip call ] [ [ next>> ] dip over [ list-each ] [ 2drop ] if ] 2bi ; inline recursive   SYMBOLS: A B C ;   A <linked-list> [ C <linked-list> list-insert ] keep [ B <linked-list> list-insert ] keep   [ . ] list-each
Give a code snippet in #Factor Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Defini...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Nemerle
Nemerle
StripChars( text : string, remove : string ) : string { def chuck = Explode(remove); Concat( "", Split(text, chuck)) }
Give a code snippet in #Nemerle Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in...
christopher/rosetta-code
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics th...
#F.23
F#
  //Be boggled? Nigel Galloway: September 19th., 2018 let N=System.Random() let fN=List.unfold(function |(0,0)->None |(n,g)->let ng=N.Next (n+g) in Some (if ng>=n then ("Black",(n,g-1)) else ("Red",(n-1,g))))(26,26) let fG n=let (n,n')::(g,g')::_=List.countBy(fun (n::g::_)->if n=g then n else g) n in sprintf "%d %s car...
Give a code snippet in #F.23 Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Haskell
Haskell
module Main where   import Network.Socket   getWebAddresses :: HostName -> IO [SockAddr] getWebAddresses host = do results <- getAddrInfo (Just defaultHints) (Just host) (Just "http") return [ addrAddress a | a <- results, addrSocketType a == Stream ]   showIPs :: HostName -> IO () showIPs host = do putStrLn $ "I...
Give a code snippet in #Haskell DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Fortran
Fortran
FUNCTION VDC(N,BASE) !Calculates a Van der Corput number... Converts 1234 in decimal to 4321 in V, and P = 10000. INTEGER N !For this integer, INTEGER BASE !In this base. INTEGER I !A copy of N that can be damaged. INTEGER P !Successive powers of BASE. INTEGER V !Accumulates dig...
Give a code snippet in #Fortran When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#TI-89_BASIC
TI-89 BASIC
Define cubic(p1,p2,p3,segs) = Prgm Local i,t,u,prev,pt 0 → pt For i,1,segs+1 (i-1.0)/segs → t © Decimal to avoid slow exact arithetic (1-t) → u pt → prev u^2*p1 + 2*t*u*p2 + t^2*p3 → pt If i>1 Then PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2]) EndIf E...
Give a code snippet in #TI-89_BASIC Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection;   public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetProper...
Give a code snippet in #C.23 Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
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.
#VBA
VBA
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x '-- absolute accuracy If d > -e And d < e Then Exit Do ...
Give a code snippet in #VBA 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/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also trivalent, ternary, or trinary...
#Forth
Forth
1 constant maybe   : tnot dup maybe <> if invert then ; : tand and ; : tor or ; : tequiv 2dup and rot tnot rot tnot and or ; : timply tnot tor ; : txor tequiv tnot ;   : t. C" TF?" 2 + + c@ emit ;   : table2. ( xt -- ) cr ." T F ?" cr ." --------" 2 true DO cr I t. ." | " 2 true DO dup I J r...
Give a code snippet in #Forth This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also...
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...
#REXX
REXX
/*REXX program finds largest left─ and right─truncatable primes ≤ 1m (or argument 1).*/ parse arg hi .; if hi=='' then hi= 1000000 /*Not specified? Then use default of 1m*/ call genP /*generate some primes, about hi ÷ 2 */ ...
Give a code snippet in #REXX 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-truncatabl...
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 ...
#AutoIt
AutoIt
#AutoIt Version: 3.2.10.0 $mystring="asdf" $reverse_string = "" $string_length = StringLen($mystring)   For $i = 1 to $string_length $last_n_chrs = StringRight($mystring, $i) $nth_chr = StringTrimRight($last_n_chrs, $i-1) $reverse_string= $reverse_string & $nth_chr Next   MsgBox(0, "Reversed string is:", $rev...
Give a code snippet in #AutoIt 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 Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Action.21
Action!
PROC Wait(BYTE frames) BYTE RTCLOK=$14 frames==+RTCLOK WHILE frames#RTCLOK DO OD RETURN   PROC Main() BYTE CH=$02FC ;Internal hardware value for last key pressed   PrintE("Program is halted for 200 frames.") PrintE("Type character to fill the buffer.") Wait(200) PutE()   DO IF CH=$FF THEN Pr...
Give a code snippet in #Action.21 Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#Raku
Raku
sub shell_sort ( @a is copy ) { loop ( my $gap = (@a/2).round; $gap > 0; $gap = ( $gap * 5 / 11 ).round ) { for $gap .. @a.end -> $i { my $temp = @a[$i];   my $j; loop ( $j = $i; $j >= $gap; $j -= $gap ) { my $v = @a[$j - $gap]; last if $v ...
Give a code snippet in #Raku 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/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...
#FALSE
FALSE
[0\1[\$@$@-][\$@$@$@$@\/*=[@\$@+@@]?1+]#%=]p: 45p;!." "28p;!. { 0 -1 }
Give a code snippet in #FALSE 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/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      ...
#Hare
Hare
use fmt; const src: str = "use fmt; const src: str = {0}{1}{0}; export fn main() void = {{fmt::printfln(src, '{0}', src)!;}};"; export fn main() void = {fmt::printfln(src, '"', src)!;};
Give a code snippet in #Hare 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/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....
#F.23
F#
  // Generate Smith Numbers. Nigel Galloway: November 6th., 2020 let fN g=Seq.unfold(fun n->match n with 0->None |_->Some(n%10,n/10)) g |> Seq.sum let rec fG(n,g) p=match g%p with 0->fG (n+fN p,g/p) p |_->(n,g) primes32()|>Seq.pairwise|>Seq.collect(fun(n,g)->[n+1..g-1])|>Seq.takeWhile(fun n->n<10000) |>Seq.filter(fun g...
Give a code snippet in #F.23 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program permutation64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstantes...
Give a code snippet in #AArch64_Assembly Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutat...
christopher/rosetta-code
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Python
Python
from decimal import Decimal import math   def h(n): 'Simple, reduced precision calculation' return math.factorial(n) / (2 * math.log(2) ** (n + 1))   def h2(n): 'Extended precision Hickerson function' return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))   for n in range(18): x = h2(n...
Give a code snippet in #Python The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyl...
christopher/rosetta-code
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1   Function LinearCombo(c As List(Of Integer)) As String Dim sb As New StringBuilder For i = 0 To c.Count - 1 Dim n = c(i) If n < 0 Then If sb.Length = 0 Then sb.Append("-") Else ...
Give a code snippet in #Visual_Basic_.NET Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\l...
christopher/rosetta-code
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Ring
Ring
  # Project : Koch curve   load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Koch curve") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,10,400,400) ...
Give a code snippet in #Ring Draw a Koch curve. See details: Koch curve
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...
#Icon_and_Unicon
Icon and Unicon
  write(image(x), if numeric(x) then " is numeric." else " is not numeric")  
Give a code snippet in #Icon_and_Unicon 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: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#jq
jq
# Input: an integer def Node: { n: ., index: -1, # -1 signifies undefined lowLink: -1, onStack: false } ;   # Input: a DirectedGraph # Output: a stream of Node ids def successors($vn): .es[$vn][];   # Input: a DirectedGraph # Output: an array of integer arrays def tarjan: . + { sccs: [], # stro...
Give a code snippet in #jq This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Tarjan's algorithm is an algorithm in graph the...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Clojure
Clojure
  (second (re-find #" (\d{1,2}:\d{1,2}:\d{1,2}) UTC" (slurp "http://tycho.usno.navy.mil/cgi-bin/timer.pl")))  
Give a code snippet in #Clojure Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Applesoft_BASIC
Applesoft BASIC
100 DATA"---------- ICE AND FIRE ------------" 110 DATA" " 120 DATA"FIRE, IN END WILL WORLD THE SAY SOME" 130 DATA"ICE. IN SAY SOME " 140 DATA"DESIRE OF TASTED I'VE WHAT FROM " 150 DATA"FIRE. FAVOR WHO THOSE WITH HOLD I " 160 DATA" ...
Give a code snippet in #Applesoft_BASIC Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separat...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Seed7
Seed7
const func integer: sumArray (in array integer: valueArray) is func result var integer: sum is 0; local var integer: value is 0; begin for value range valueArray do sum +:= value; end for; end func;   const func integer: prodArray (in array integer: valueArray) is func result var int...
Give a code snippet in #Seed7 Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#Nim
Nim
proc shellSort[T](a: var openarray[T]) = var h = a.len while h > 0: h = h div 2 for i in h ..< a.len: let k = a[i] var j = i while j >= h and k < a[j-h]: a[j] = a[j-h] j -= h a[j] = k   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] shellSort a echo a
Give a code snippet in #Nim 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/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#REXX
REXX
char1 = "A" char2 = 'A' str = "this is a string" another = 'this is also a string' escape1 = "that's it!" escape2 = 'that''s it!'
Give a code snippet in #REXX Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#VBA
VBA
  Option Explicit   Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub   Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 'Count On Error Resume Next Limite_Recursivite Cpt 'recurse On Error GoTo 0 Limite_Recursivite = Cpt 'return End Fun...
Give a code snippet in #VBA Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Sidef
Sidef
var angle_deg = 45; var angle_rad = Num.pi/4;   for arr in [ [sin(angle_rad), sin(deg2rad(angle_deg))], [cos(angle_rad), cos(deg2rad(angle_deg))], [tan(angle_rad), tan(deg2rad(angle_deg))], [cot(angle_rad), cot(deg2rad(angle_deg))], ] { say arr.join(" "); }   for n in [ asin(sin(angle_rad)), ...
Give a code snippet in #Sidef 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 evalu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#EasyLang
EasyLang
len prims[] 100 max = sqrt len prims[] tst = 2 while tst <= max if prims[tst] = 0 i = tst * tst while i < len prims[] prims[i] = 1 i += tst . . tst += 1 . i = 2 while i < len prims[] if prims[i] = 0 print i . i += 1 .
Give a code snippet in #EasyLang This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes ...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Julia
Julia
i,j,m,d,seed = 55,24,10^9,34,292929 # parameters s = Array{Int32}(undef,i); r = similar(s) s[1:2] = [seed,1] # table initialization for n = 3:i; (s[n] = s[n-2]-s[n-1]) < 0 && (s[n] += m) end t = 1; for u=1:i; (global t+=d)>i && (t-=i); r[u]=s[t] end # permutation, r = s[(d*(1:i) .% i).+1]   u,...
Give a code snippet in #Julia A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {...
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#FreeBASIC
FreeBASIC
#define dx 0.0001   'read in the data; I reordered them in descending order of radius 'This maximises our chance of being able to break early, saving run time, 'and we needn't bother finding out which circles are entirely inside others data -0.5263668798,1.7315156631,1.4428514068 data -0.1403562064,0.2437382535,1.38049...
Give a code snippet in #FreeBASIC Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Brainf.2A.2A.2A
Brainf***
  ===========[ ARRAY DATA STRUCTURE   AUTHOR: Keith Stellyes WRITTEN: June 2016   This is a zero-based indexing array data structure, it assumes the following precondition:   >INDEX<|NULL|VALUE|NULL|VALUE|NULL|VALUE|NULL   (Where >< mark pointer position, and | separates addresses)   It relies heavily on [>] and [<] b...
Give a code snippet in #Brainf.2A.2A.2A This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it,...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#BASIC
BASIC
f = freefile filename$ = "input.txt" open f, filename$   lineapedida = 7 cont = 0 while not (eof(f)) linea$ = readline(f) cont += 1 if cont = lineapedida then if trim(linea$) = "" then print "The 7th line is empty" else print linea$ exit while end if end while if cont < lineapedida then print "There a...
Give a code snippet in #BASIC Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it i...
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...
#C
C
#include <stdio.h> //~ Take a number n and return a function that takes a number i #define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \ static __typeof__(n) _n=n; LOGIC; } //~ have it return n incremented by the accumulation of i #define LOGIC return _n+=i ACCUMULATOR(x,1.0) ACCUMULATOR(y,3) ACCUMUL...
Give a code snippet in #C 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/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#ALGOL_W
ALGOL W
begin  % replaces M with it's reduced row echelon form  %  % M should have bounds ( 0 :: rMax, 0 :: cMax )  % procedure toReducedRowEchelonForm ( real array M ( *, * )  ; integer value rMax, cMax ) ; begi...
Give a code snippet in #ALGOL_W Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is conveni...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#OxygenBasic
OxygenBasic
  'GENERIC BITMAP   type pixel byte r,g,b   '=========== class BitMap '===========   % sp sizeof(pixel) sys wx,wy,px,py string buf sys pb method Constructor(sys x=640,y=480) { wx=x : wy=y : buf=nuls x*y*sp : pb=strptr buf} method Destructor() {buf="" : wx=0 : wy=0 : pb=0} method GetPixel(sys x,y...
Give a code snippet in #OxygenBasic Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain ...
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...
#Logtalk
Logtalk
  :- object(spliting).   :- public(convert/2). :- mode(convert(+atom, -atom), one).   convert(StringIn, StringOut) :- atom_chars(StringIn, CharactersIn), phrase(split(',', Tokens), CharactersIn), phrase(split('.', Tokens), CharactersOut), atom_chars(StringOut, CharactersOut)....
Give a code snippet in #Logtalk 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#XBS
XBS
settype Bearing = {Angle:number} class Bearing { private method construct(Angle:number=0) self.Angle=(((Angle%360)+540)%360)-180; method ToString():string send tostring(math.nround(self.Angle,4))+"°"; private method __sub(b2:Bearing):Bearing{ send new Bearing(self.Angle-b2.Angle); } }   c...
Give a code snippet in #XBS Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -1...
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.
#XBasic
XBasic
  PROGRAM "multiplicationtables" VERSION "0.0001"   DECLARE FUNCTION Entry()   FUNCTION Entry() $N = 12 FOR j@@ = 1 TO $N - 1 PRINT FORMAT$("### ", j@@); NEXT j@@ PRINT FORMAT$("###", $N) FOR j@@ = 0 TO $N - 1 PRINT "----"; NEXT j@@ PRINT "+" FOR i@@ = 1 TO $N FOR j@@ = 1 TO $N IF j@@ ...
Give a code snippet in #XBasic 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/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.
#BBC_BASIC
BBC BASIC
VDU 23,22,453;453;8,20,16,128 *FONT Arial,28   DIM Board%(8,8) Board%() = %111111111   FOR L% = 0 TO 9:P% = L%*100 LINE 2,P%+2,902,P%+2 IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4 LINE P%+2,2,P%+2,902 IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,...
Give a code snippet in #BBC_BASIC 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/String_prepend
String prepend
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 |...
#Tcl
Tcl
set s "llo world" set s "he$s" puts $s
Give a code snippet in #Tcl 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/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#newLISP
newLISP
; Here are some simpler functions to help us:   (define (divisible? larger-number smaller-number) (zero? (% larger-number smaller-number)))   (define (int-root number) (floor (sqrt number)))   (define (even-prime? number) (= number 2))   ; Trial division for odd numbers   (define (find-odd-factor? odd-number) (catc...
Give a code snippet in #newLISP Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Kronecker_product_based_fractals
Kronecker product based fractals
This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matrix   (filled with 0/1)   we ...
#Go
Go
package main   import "fmt"   type matrix [][]int   func (m1 matrix) kroneckerProduct(m2 matrix) matrix { m := len(m1) n := len(m1[0]) p := len(m2) q := len(m2[0]) rtn := m * p ctn := n * q r := make(matrix, rtn) for i := range r { r[i] = make([]int, ctn) // all elements zero by ...
Give a code snippet in #Go This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matr...
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 ...
#Ada
Ada
generic type Base_Type is mod <>; Multiplyer, Adder: Base_Type; Output_Divisor: Base_Type := 1; package LCG is   procedure Initialize(Seed: Base_Type); function Random return Base_Type; -- changes the state and outputs the result   end LCG;
Give a code snippet in #Ada 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_{...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#LabVIEW
LabVIEW
  {def arithmetic {lambda {:x :y} {S.map {{lambda {:x :y :op} {br}applying :op on :x & :y returns {:op :x :y}} :x :y} + - * / % pow max min = > <}}} -> arithmetic   {arithmetic 8 12} -> applying + on 8 & 12 returns 20 applying - on 8 & 12 returns -4 applying * on 8 & 12 returns 96 ap...
Give a code snippet in #LabVIEW 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 Operation...
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...
#Slate
Slate
x@(Syntax LoadVariable traits) swapWith: y@(Syntax LoadVariable traits) &environment: env "A macro that expands into simple code swapping the values of two variables in the current scope." [ env ifNil: [error: 'Cannot swap variables outside of a method']. tmpVar ::= env addVariable. {tmpVar store: x variable load...
Give a code snippet in #Slate 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 genericit...
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#C.2B.2B
C++
#include <random> #include <vector> #include <iostream>   #define MAX_N 20 #define TIMES 1000000   /** * Used to generate a uniform random distribution */ static std::random_device rd; //Will be used to obtain a seed for the random number engine static std::mt19937 gen(rd()); //Standard mersenne_twister_engine seede...
Give a code snippet in #C.2B.2B Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Kotlin
Kotlin
// version 1.1.3   typealias Vector = DoubleArray typealias Matrix = Array<Vector>   fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } // permutation val q = IntArray(n) { it } // inverse permutation val d = IntArray(n) { -1 } // direction = 1 or -1 var sign = 1...
Give a code snippet in #Kotlin linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Stata
Stata
a = 1,-2,-3,-4,5 sum(a) -3 (-1)^mod(sum(a:<0),2)*exp(sum(log(abs(a)))) -120
Give a code snippet in #Stata Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Python
Python
from __future__ import division, print_function from math import gcd, sqrt     def hero(a, b, c): s = (a + b + c) / 2 a2 = s * (s - a) * (s - b) * (s - c) return sqrt(a2) if a2 > 0 else 0     def is_heronian(a, b, c): a = hero(a, b, c) return a > 0 and a.is_integer()     def gcd3(x, y, z): retur...
Give a code snippet in #Python Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a +...
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
#C2
C2
module hello_world; import stdio as io;   func i32 main(i32 argc, char** argv) { io.printf("Hello World!\n"); return 0; }
Give a code snippet in #C2 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   H...
christopher/rosetta-code
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks 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) In computational number theory, the Tonelli–Shanks algor...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program tonshan64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../inc...
Give a code snippet in #AArch64_Assembly This page uses content from Wikipedia. The original article was at Tonelli-Shanks 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) In computation...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#jq
jq
# produce an array of length n that is 1 at i and 0 elsewhere def indicator(i;n): [range(0;n) | 0] | .[i] = 1;   # Identity matrix: def identity(n): reduce range(0;n) as $i ([]; . + [indicator( $i; n )] );   def direct_matrix_exp(n): . as $in | if n == 0 then identity($in|length) else reduce range(1;n) as $i ($...
Give a code snippet in #jq Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code