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/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET a=1: LET g=1/SQR 2 20 LET ta=a 30 LET a=(a+g)/2 40 LET g=SQR (ta*g) 50 IF a<ta THEN GO TO 20 60 PRINT a  
Give a code snippet in #ZX_Spectrum_Basic This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write ...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Perl
Perl
my @prisoner = 0 .. 40; my $k = 3; until (@prisoner == 1) { push @prisoner, shift @prisoner for 1 .. $k-1; shift @prisoner; }   print "Prisoner @prisoner survived.\n"
Give a code snippet in #Perl Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Curry
Curry
-- quicksort using higher-order functions:   qsort :: [Int] -> [Int] qsort [] = [] qsort (x:l) = qsort (filter (<x) l) ++ x : qsort (filter (>=x) l)   goal = qsort [2,3,1,0]
Give a code snippet in #Curry 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/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Standard_ML
Standard ML
fun bitwise_ints (a, b) = ( print ("a and b: " ^ IntInf.toString (IntInf.andb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n"); print ("a or b: " ^ IntInf.toString (IntInf.orb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n"); print ("a xor b: " ^ IntInf.toString (IntInf.xorb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\...
Give a code snippet in #Standard_ML 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#OCaml
OCaml
open Num   let get_input () = num_of_int ( try int_of_string Sys.argv.(1) with _ -> 10)   let get_max_steps () = try int_of_string Sys.argv.(2) with _ -> 50   let read_program () = let line = read_line () in let words = Str.split (Str.regexp " +") line in List.map num_of_string words   let i...
Give a code snippet in #OCaml FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initia...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#OCaml
OCaml
# #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;;   # #load "xml-light.cma" ;;   # let data = [ ("April", "Bubbly: I'm > Tam and <= Emily"); ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""); ("Emily", "Short & shrift"); ] in let tags = List.map (fun (name, co...
Give a code snippet in #OCaml Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> el...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Sidef
Sidef
class Graph(*args) {   struct Node { String name, Array edges = [], Number dist = Inf, prev = nil, Bool visited = false, }   struct Edge { Number weight, Node vertex, }   has g = Hash()   method init { args.each { |a| se...
Give a code snippet in #Sidef This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Picat
Picat
import util.   go =>   L1 = ["a","b","c"], L2 = ["A","B","C"], L3 = ["1","2","3"],   println("foreach loop:"), foreach({A,B,C} in zip(L1,L2,L3)) println([A,B,C].join('')) end, nl,   println("list comprehension/n:"), println( [[A,B,C].join('') : {A,B,C} in zip(L1,L2,L3)].join("\n")), nl,    % W...
Give a code snippet in #Picat Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this exam...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Modula-3
Modula-3
MODULE Bogo EXPORTS Main;   IMPORT IO, Fmt, Random;   VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5}; count := 0;   PROCEDURE Shuffle(VAR a: ARRAY OF INTEGER) = VAR temp: INTEGER; BEGIN WITH rand = NEW(Random.Default).init() DO FOR i := FIRST(a) TO LAST(a) - 1 DO WITH j = rand.integer(i, LAS...
Give a code snippet in #Modula-3 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Delphi
Delphi
function ReverseString(const InString: string): string; var i: integer; begin for i := Length(InString) downto 1 do Result := Result + InString[i]; end;
Give a code snippet in #Delphi 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/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#DCL
DCL
$! looper.com procedure $ i = 10 $ loop: $ show time $ wait 'p1 $ i = i - 1 $ if i .gt. 0 then $ goto loop
Give a code snippet in #DCL Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
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.
#Sidef
Sidef
var ary = [1, 2, 3, 4, 5]; say ary.sum; # => 15 say ary.prod; # => 120
Give a code snippet in #Sidef Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Elixir
Elixir
defmodule Gray_code do use Bitwise def encode(n), do: bxor(n, bsr(n,1))   def decode(g), do: decode(g,0)   def decode(0,n), do: n def decode(g,n), do: decode(bsr(g,1), bxor(g,n)) end   Enum.each(0..31, fn(n) -> g = Gray_code.encode(n) d = Gray_code.decode(g)  :io.fwrite("~2B : ~5.2.0B : ~5.2.0B : ~5.2.0B...
Give a code snippet in #Elixir Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Zig
Zig
const std = @import("std");   pub fn main() !void { const stdout_wr = std.io.getStdOut().writer(); var i: u8 = 1; while (i < 5) : (i += 1) { var j: u8 = 1; while (j <= i) : (j += 1) try stdout_wr.writeAll("*"); try stdout_wr.writeAll("\n"); } }
Give a code snippet in #Zig “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structure...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#MiniScript
MiniScript
code = input("Enter HQ9+ program: ")   sing = function() for i in range(99,2) print i + " bottles of beer on the wall, " + i + " bottles of beer" print "Take one down, pass it around, " + (i-1) + " bottle" + "s"*(i>2) + " of beer on the wall" end for print "1 bottle of beer on the wall, 1 bo...
Give a code snippet in #MiniScript Task Implement a   HQ9+   interpreter or compiler.
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...
#Axe
Axe
Disp sin(43)▶Dec,i Disp cos(43)▶Dec,i Disp tan⁻¹(10,10)▶Dec,i
Give a code snippet in #Axe 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 evaluat...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#AutoHotkey
AutoHotkey
Loop MsgBox SPAM `n
Give a code snippet in #AutoHotkey Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach  ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#D
D
void main() { import std.stdio; import std.algorithm: startsWith, endsWith, find, countUntil;   "abcd".startsWith("ab").writeln; // true "abcd".endsWith("zn").writeln; // false "abab".find("bb").writeln; // empty array (no match) "abcd".find("bc").writeln; // "b...
Give a code snippet in #D 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#CoffeeScript
CoffeeScript
  F = (n) -> if n is 0 then 1 else n - M F n - 1   M = (n) -> if n is 0 then 0 else n - F M n - 1   console.log [0...20].map F console.log [0...20].map M  
Give a code snippet in #CoffeeScript Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Nim
Nim
import math, strutils   func nosqr(n: int): seq[int] = result = newSeq[int](n) for i in 1..n: result[i - 1] = i + i.float.sqrt.toInt   func issqr(n: int): bool = sqrt(float(n)).splitDecimal().floatpart < 1e-7     echo "Sequence for n = 22:" echo nosqr(22).join(" ")   for i in nosqr(1_000_000 - 1): assert no...
Give a code snippet in #Nim Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#C.2B.2B
C++
  #include "stdafx.h" #include <iostream> #include <math.h> using namespace std;   bool isPrime(double number) { for (double i = number - 1; i >= 2; i--) { if (fmod(number, i) == 0) return false; } return true; } int main() { double i = 42; int n = 0; while (n < 42) { ...
Give a code snippet in #C.2B.2B Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop whic...
christopher/rosetta-code
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Haskell
Haskell
import Text.Printf import Data.List   juggler :: Integer -> [Integer] juggler = takeWhile (> 1) . iterate (\x -> if odd x then isqrt (x*x*x) else isqrt x)   task :: Integer -> IO () task n = printf s n (length ns + 1) (i :: Int) (show...
Give a code snippet in #Haskell Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in t...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#FBSL
FBSL
#APPTYPE CONSOLE   FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING DIM sTemp AS STRING = "" DIM c AS STRING FOR DIM i = 1 TO LEN(s) c = MID(s, i, 1) IF INSTR("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c, 0, 1) THEN sTemp = stemp & c END IF NEXT RETURN sTemp END FUNCTION   FUNCTION IsPalindrome(BYVAL s AS STRING) A...
Give a code snippet in #FBSL A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#Tcl
Tcl
set PI 3.1415927 fconfigure stdout -buffering none puts -nonewline "Enter latitude => "; gets stdin lat puts -nonewline "Enter longitude => "; gets stdin lng puts -nonewline "Enter legal meridian => "; gets stdin ref puts ""   set slat [expr {sin($lat*$PI/180)}] puts [format " sine of latitude:  %8g" $sl...
Give a code snippet in #Tcl Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#Run_BASIC
Run BASIC
open file.txt" for binary as #f numChars = 1 ' specify number of characters to read a$ = input$(#f,numChars) ' read number of characters specified b$ = input$(#f,1) ' read one character close #f
Give a code snippet in #Run_BASIC Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should s...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Doors is type Door_State is (Closed, Open); type Door_List is array(Positive range 1..100) of Door_State; The_Doors : Door_List := (others => Closed); begin for I in 1..100 loop for J in The_Doors'range loop if J mod I = 0 then ...
Give a code snippet in #Ada There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...)...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#VBScript
VBScript
option explicit   class List private theList private nOccupiable private nTop   sub class_initialize nTop = 0 nOccupiable = 100 redim theList( nOccupiable ) end sub   public sub store( x ) if nTop >= nOccupiable then nOccupiable = nOccupiable + 100 redim preserve theList( nOccupiable ) end if th...
Give a code snippet in #VBScript Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, an...
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 ...
#Action.21
Action!
SET EndProg=*
Give a code snippet in #Action.21 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#Java
Java
import java.text.DateFormat; import java.util.Date; import java.util.TimeZone;   public class DateTest{ public static void main(String[] args) { Date date = new Date(0); DateFormat format = DateFormat.getDateTimeInstance(); format.setTimeZone(TimeZone.getTimeZone("UTC")); System.out....
Give a code snippet in #Java Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Delphi
Delphi
proc move(byte n, src, via, dest) void: if n>0 then move(n-1, src, dest, via); writeln("Move disk from pole ",src," to pole ",dest); move(n-1, via, src, dest) fi corp   proc nonrec main() void: move(4, 1, 2, 3) corp
Give a code snippet in #Delphi Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Racket
Racket
  #lang racket   (define (next s) (define v (make-vector 10 0)) (for ([c s]) (define d (- (char->integer #\9) (char->integer c))) (vector-set! v d (add1 (vector-ref v d)))) (string-append* (for/list ([x v] [i (in-range 9 -1 -1)] #:when (> x 0)) (format "~a~a" x i))))   (define (seq-of ...
Give a code snippet in #Racket There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#FreeBASIC
FreeBASIC
  Dim As String text1 = " " & Chr(10) & _ "<<'FOO' " & Chr(10) & _ " 'jaja', `esto`" & Chr(10) & _ " <simula>" & Chr(10) & _ " \un\" & Chr(10) & _ !" ${ejemplo} de \"heredoc\"" & Chr(10) & _ " en FreeBASIC."   Dim As String text2 = "Esta es la primera linea." & Chr(10) & _ "Esta es la segunda linea." & Chr(10) & _...
Give a code snippet in #FreeBASIC A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) fol...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Ring
Ring
    Load "guilib.ring"   /* +--------------------------------------------------------------------------- + Program Name : Draw Barnsley Fern + Purpose  : Draw Fern using Quadratic Equation and Random Number +--------------------------------------------------------------------------- */   ###------...
Give a code snippet in #Ring A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#JavaScript
JavaScript
function stripComments(s) { var re1 = /^\s+|\s+$/g; // Strip leading and trailing spaces var re2 = /\s*[#;].+$/g; // Strip everything after # or ; to the end of the line, including preceding spaces return s.replace(re1,'').replace(re2,''); }     var s1 = 'apples, pears # and bananas'; var s2 = 'apples, pears ; a...
Give a code snippet in #JavaScript Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line...
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#BASIC
BASIC
10 DEFINT A-Z: E=500 20 DIM P(E): P(0)=-1: P(1)=-1 30 FOR I=2 TO SQR(E) 40 IF NOT P(I) THEN FOR J=I*2 TO E STEP I: P(J)=-1: NEXT 50 NEXT 60 FOR I=B TO E: IF P(I) GOTO 100 70 J=I: S=0 80 IF J>0 THEN S=S+J MOD 10: J=J\10: GOTO 80 90 IF NOT P(S) THEN N=N+1: PRINT I, 100 NEXT 110 PRINT: PRINT N;" additive primes found belo...
Give a code snippet in #BASIC Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Clojure
Clojure
(let [n (range 1 8)] (for [police n sanitation n fire n  :when (distinct? police sanitation fire)  :when (even? police)  :when (= 12 (+ police sanitation fire))] (println police sanitation fire)))
Give a code snippet in #Clojure There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#Perl
Perl
#!/usr/bin/perl   use strict; # interpreter.pl - execute a flatAST use warnings; # http://www.rosettacode.org/wiki/Compiler/AST_interpreter use integer;   my %variables;   tree()->run;   sub tree { my $line = <> // die "incomplete tree\n"; (local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line...
Give a code snippet in #Perl An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#LOLCODE
LOLCODE
  HAI 1.2 HOW DUZ I fibonacci YR N EITHER OF BOTH SAEM N AN 1 AN BOTH SAEM N AN 0 O RLY? YA RLY, FOUND YR 1 NO WAI I HAS A N1 I HAS A N2 N1 R DIFF OF N AN 1 N2 R DIFF OF N AN 2 N1 R fibonacci N1 N2 R fibonacci N2 FOUND YR SUM OF N1 AN N2 OIC IF U SAY SO KTHXBYE  
Give a code snippet in #LOLCODE The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions a...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#ALGOL_W
ALGOL W
begin  % declare the three arrays  % string(1) array a, b ( 1 :: 3 ); integer array c ( 1 :: 3 );  % initialise the arrays - have to do this element by element in Algol W  % a(1) := "a"; a(2) := "b"; a(3) := "c"; b(1) := "A"; b(2) := "B"; b(3) := "...
Give a code snippet in #ALGOL_W Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this ex...
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
#Neko
Neko
/** hellonnl.neko Tectonics: nekoc hellonnl.neko neko hellonnl   -or-   nekoc hellonnl.neko nekotools boot hellonnl.n ./hellonnl */   $print("Goodbye, World!");
Give a code snippet in #Neko Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#Ruby
Ruby
class Forest_Fire Neighborhood = [-1,0,1].product([-1,0,1]) - [0,0] States = {empty:" ", tree:"T", fire:"#"}   def initialize(xsize, ysize=xsize, p=0.5, f=0.01) @xsize, @ysize, @p, @f = xsize, ysize, p, f @field = Array.new(xsize+1) {|i| Array.new(ysize+1, :empty)} @generation = 0 end   def evolve...
Give a code snippet in #Ruby This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and S...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#XPL0
XPL0
string 0; \use zero-terminated strings int MaxLen, Pass, I, Ch, Ch0; char Word(25); def LF=$0A, CR=$0D, EOF=$1A; [FSet(FOpen("unixdict.txt", 0), ^I); MaxLen:= 0; for Pass:= 1 to 2 do [OpenI(3); repeat I:= 0; Ch0:= 0; loop [repeat Ch:= ChIn(3) until Ch # CR; ...
Give a code snippet in #XPL0 An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#GAP
GAP
MultiFactorial := function(n, k) local r; r := 1; while n > 1 do r := r*n; n := n - k; od; return r; end;   PrintArray(List([1 .. 10], n -> List([1 .. 5], k -> MultiFactorial(n, k)))); [ [ 1, 1, 1, 1, 1 ], [ 2, 2, 2, 2,...
Give a code snippet in #GAP The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Swift
Swift
func luhn(_ number: String) -> Bool { return number.reversed().enumerated().map({ let digit = Int(String($0.element))! let even = $0.offset % 2 == 0 return even ? digit : digit == 9 ? 9 : digit * 2 % 9 }).reduce(0, +) % 10 == 0 }   luhn("49927398716") // true luhn("49927398717") // false
Give a code snippet in #Swift The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#zkl
zkl
var [const] MsgHash=Import("zklMsgHash"), Curl=Import("zklCurl");   icon:=Curl().get("http://rosettacode.org/favicon.ico"); //-->(Data(4,331),693,0) icon=icon[0][icon[1],*]; // remove header iconEncoded:=MsgHash.base64encode(icon); iconDecoded:=MsgHash.base64decode(iconEncoded); File("rosettaCodeIcon.ico","wb").write(i...
Give a code snippet in #zkl See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Logtalk
Logtalk
:- object(foo).   :- public(bar/1). bar(42).   :- end_object.
Give a code snippet in #Logtalk Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#Io
Io
List do ( selectionSortInPlace := method( size repeat(idx, swapIndices(idx, indexOf(slice(idx, size) min)) ) ) )   l := list(-1, 4, 2, -9) l selectionSortInPlace println # ==> list(-9, -1, 2, 4)
Give a code snippet in #Io Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#IS-BASIC
IS-BASIC
100 PROGRAM "SpiralMa.bas" 110 TEXT 80 120 INPUT PROMPT "Enter size of matrix (max. 10): ":N 130 NUMERIC A(1 TO N,1 TO N) 140 CALL INIT(A) 150 CALL WRITE(A) 160 DEF INIT(REF T) 170 LET BCOL,BROW,COL,ROW=1:LET TCOL,TROW=N:LET DIR=0 180 FOR I=0 TO N^2-1 190 LET T(COL,ROW)=I 200 SELECT CASE DIR 210 CASE 0 ...
Give a code snippet in #IS-BASIC Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Never
Never
for (i = 0; i < 10; i += 3)
Give a code snippet in #Never Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Inc...
christopher/rosetta-code
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#GW-BASIC
GW-BASIC
10 FOR T = 0 TO 9 20 FOR U = 1 TO 10 30 N = 10*T + U 40 GOSUB 100 50 PRINT USING "## ";M; 60 NEXT U 70 PRINT 80 NEXT T 90 END 100 IF N = 1 THEN M = 1 : RETURN 110 M = 1 : F = 2 120 IF N MOD (F*F) = 0 THEN M = 0 : RETURN 130 IF N MOD F = 0 THEN GOSUB 170 140 F = F + 1 150 IF F <= N THEN GOTO 120 160 RETURN 170 M = -M 1...
Give a code snippet in #GW-BASIC The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#BQN
BQN
rlwrap ./BQN
Give a code snippet in #BQN Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-n...
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...
#PowerShell
PowerShell
function IsPrime ( [int] $num ) { $isprime = @{} 2..[math]::sqrt($num) | Where-Object { $isprime[$_] -eq $null } | ForEach-Object { $_ $isprime[$_] = $true for ( $i=$_*$_ ; $i -le $num; $i += $_ ) { $isprime[$i] = $false } } 2..$num | Where-Object { $isprime[$_] -...
Give a code snippet in #PowerShell 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-trun...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#langur
langur
val .x, .y = true, null   writeln .x == null writeln .y == null writeln .x ==? null writeln .y ==? null   # null not a "truthy" result writeln if(null: 0; 1)
Give a code snippet in #langur Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your lang...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#VBScript
VBScript
  Function lcs(string1,string2) For i = 1 To Len(string1) tlcs = tlcs & Mid(string1,i,1) If InStr(string2,tlcs) Then If Len(tlcs) > Len(lcs) Then lcs = tlcs End If Else tlcs = "" End If Next End Function   WScript.Echo lcs(WScript.Arguments(0),WScript.Arguments(1))  
Give a code snippet in #VBScript Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are conse...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PHP
PHP
function bogosort($l) { while (!in_order($l)) shuffle($l); return $l; }   function in_order($l) { for ($i = 1; $i < count($l); $i++) if ($l[$i] < $l[$i-1]) return FALSE; return TRUE; }
Give a code snippet in #PHP 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/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#FunL
FunL
import lists.foldr   def horner( poly, x ) = foldr( \a, b -> a + b*x, 0, poly )   println( horner([-19, 7, -4, 6], 3) )
Give a code snippet in #FunL A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Rust
Rust
use std::cmp::Ordering;   #[derive(Debug)] struct Employee { name: String, category: String, }   impl Employee { fn new(name: &str, category: &str) -> Self { Employee { name: name.into(), category: category.into(), } } }   impl PartialEq for Employee { fn eq(&...
Give a code snippet in #Rust 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/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 org 100h section .text ;;; Calculate hamming weights of 3^0 to 3^29. ;;; 3^29 needs a 48-bit representation, which ;;; we'll put in BP:SI:DI. xor bp,bp ; BP:SI:DI = 1 xor si,si xor di,di inc di mov cx,30 ;;; Calculate pop count of BP:SI:DI pow3s: push bp ; Keep state push si push di xo...
Give a code snippet in #8086_Assembly Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   p...
christopher/rosetta-code
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#REXX
REXX
/*REXX program verifies if a horizontal ray from point P intersects a polygon. */ call points 5 5, 5 8, -10 5, 0 5, 10 5, 8 5, 10 10 A= 2.5; B= 7.5 /* ◄───── used for shorter arguments (below).*/ call poly 0 0, 10 0, 10 10, 0 10 ...
Give a code snippet in #REXX This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#JavaScript
JavaScript
// USING A LIST MONAD DIRECTLY, WITHOUT SPECIAL SYNTAX FOR LIST COMPREHENSIONS   (function (n) {   return mb(r(1, n), function (x) { // x <- [1..n] return mb(r(1 + x, n), function (y) { // y <- [1+x..n] return mb(r(1 + y, n), function (z) { // z <- [1+y..n]   return x * x + y * y === z * z ? [...
Give a code snippet in #JavaScript A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops a...
christopher/rosetta-code
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Nim
Nim
import sequtils, strformat   func mertensNumbers(max: int): seq[int] = result = repeat(1, max + 1) for n in 2..max: for k in 2..n: dec result[n], result[n div k]   const Max = 1000 let mertens = mertensNumbers(Max)   echo "First 199 Mertens numbers:" const Count = 200 var column = 0 for i in 0..<Count: ...
Give a code snippet in #Nim The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Racket
Racket
# Raku supports multi dimension arrays natively. There are no arbitrary limits on the number of dimensions or maximum indices. Theoretically, you could have an infinite number of dimensions of infinite length, though in practice more than a few dozen dimensions gets unwieldy. An infinite maximum index is a fairly commo...
Give a code snippet in #Racket For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new val...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#DCL
DCL
{}
Give a code snippet in #DCL Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ReScript
ReScript
while true { Js.log("SPAM") }
Give a code snippet in #ReScript Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   L...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#SPAD
SPAD
(1) -> integer READ()$Lisp + integer READ()$Lisp 333 444   (1) 777 Type: PositiveInteger
Give a code snippet in #SPAD A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of...
#C
C
#include <math.h> #include <stdio.h> #include <stdint.h>   int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; }   // Constants // First generator const static int64_t a1[3] = ...
Give a code snippet in #C MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* l...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Ring
Ring
  haystack = ["alpha","bravo","charlie","delta","echo","foxtrot","golf", "hotel","india","juliet","kilo","lima","mike","needle", "november","oscar","papa","quebec","romeo","sierra","tango", "needle","uniform","victor","whisky","x-ray","yankee","zulu"]   needle = "needle" maxindex = len(haystack)   for index = 1 to ...
Give a code snippet in #Ring Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PL.2FI
PL/I
cocktail: procedure (A); declare A(*) fixed; declare t fixed; declare stable bit (1); declare (i, n) fixed binary (31);   n = hbound(A,1); do until (stable); stable = '1'b; do i = 1 to n-1, n-1 to 1 by -1; if A(i) > A(i+1) then do; stable = '0'b; /* still unsorted, so ...
Give a code snippet in #PL.2FI Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Euphoria
Euphoria
for i = 10 to 0 by -1 do ? i end for
Give a code snippet in #Euphoria Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Inc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#CoffeeScript
CoffeeScript
# This is a simple version of mergesort that returns brand-new arrays. # A more sophisticated version would do more in-place optimizations. merge_sort = (arr) -> if arr.length <= 1 return (elem for elem in arr) m = Math.floor(arr.length / 2) arr1 = merge_sort(arr.slice 0, m) arr2 = merge_sort(arr.slice m) ...
Give a code snippet in #CoffeeScript 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 | Q...
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
input s:  !print\ s  !decode!utf-8 !read-line!stdin local :astring input "Enter a string: " true while: try: to-num input "Enter the number 75000: " /= 75000 catch value-error: true
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#zkl
zkl
L("Krusty","Charlie","Bozo","Bozo").index("Charlie") //--> 1 L("Krusty","Charlie","Bozo","Bozo").index("fred") //--> throws index error
Give a code snippet in #zkl Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#ALGOL_68
ALGOL 68
[]UNION(STRING, INT, PROC(REF FILE)VOID) collection = ("Mary","Had",1,"little","lamb.",new line);   FOR index FROM LWB collection TO UPB collection DO print((collection[index]," ")) OD
Give a code snippet in #ALGOL_68 Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Io
Io
file := File clone openForReading("./unixdict.txt") words := file readLines file close   maxLen := 0 orderedWords := list() words foreach(word, if( (word size >= maxLen) and (word == (word asMutable sort)), if( word size > maxLen, maxLen = word size orderedWords empty ) ...
Give a code snippet in #Io An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally a...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Factor
Factor
USING: io kernel math math.parser sequences ;   : thue-morse ( seq n -- seq' ) [ [ ] [ [ 1 bitxor ] map ] bi append ] times ;   : print-tm ( seq -- ) [ number>string ] map "" join print ;   7 <iota> [ { 0 } swap thue-morse print-tm ] each
Give a code snippet in #Factor Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Icon_and_Unicon
Icon and Unicon
procedure main() digits := "123456789" every !digits :=: ?digits num := digits[1+:4] repeat if score(num, getGuess(num)) then break write("Good job.") end   procedure getGuess(num) repeat { writes("Enter a guess: ") guess := read() | stop("Quitter!") if *(guess ** '123456...
Give a code snippet in #Icon_and_Unicon Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#Kotlin
Kotlin
// version 1.1.2   class Node<T: Number>(var data: T, var next: Node<T>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next ...
Give a code snippet in #Kotlin Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definiti...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#NewLISP
NewLISP
; file: date-format.lsp ; url: http://rosettacode.org/wiki/Date_format ; author: oofoe 2012-02-01   ; The "now" function returns the current time as a list. A time zone ; offset in minutes can be supplied. The example below is for Eastern ; Standard Time. NewLISP's implicit list indexing is used to extract ; the f...
Give a code snippet in #NewLISP This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Oz
Oz
functor import Application Open System define fun {IsAlreadyRunning} try S = {New Open.socket init} in {S bind(takePort:12345)} false catch system(os(os "bind" ...) ...) then true end end   if {IsAlreadyRunning} then {System.showInfo "Exiting because already running."} ...
Give a code snippet in #Oz This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#PicoLisp
PicoLisp
(de dining (Name State) (loop (prinl Name ": " State) (state 'State # Dispatch according to state (thinking 'hungry) # If thinking, get hungry (hungry # If hungry, grab random fork (if (rand T) (and ...
Give a code snippet in #PicoLisp The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and e...
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 ...
#ALGOL_68
ALGOL 68
CO PR READ "shell_sort.a68" PR CO MODE TYPE = INT;   PROC in place shell sort = (REF[]TYPE seq)REF[]TYPE:( INT inc := ( UPB seq + LWB seq + 1 ) OVER 2; WHILE inc NE 0 DO FOR index FROM LWB seq TO UPB seq DO INT i := index; TYPE el = seq[i]; WHILE ( i - LWB seq >= inc...
Give a code snippet in #ALGOL_68 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Erlang
Erlang
  -module(factors). -export([factors/1,kthfactor/2]).   factors(N) -> factors(N,2,[]).   factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc).     % is integer N factorable into M primes? kthfactor(N,M) -> case l...
Give a code snippet in #Erlang Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was ch...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#ML
ML
ntos ` ston "1234" + 1;  
Give a code snippet in #ML Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#Ada
Ada
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; with Ada.Text_IO; use Ada.Text_IO;   procedure Forest_Fire is type Cell is (Empty, Tree, Fire); type Board is array (Positive range <>, Positive range <>) of Cell; procedure Step (S : in out Board; P, F : Float; Dice : Generator) is...
Give a code snippet in #Ada This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#Oz
Oz
declare [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   fun {GetPage RawUrl} Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)} Url = {VirtualString.toString RawUrl} OutParams HttpResponseParams i...
Give a code snippet in #Oz Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 202...
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...
#Raku
Raku
sub is-k-almost-prime($n is copy, $k) returns Bool { loop (my ($p, $f) = 2, 0; $f < $k && $p*$p <= $n; $p++) { $n /= $p, $f++ while $n %% $p; } $f + ($n > 1) == $k; }   for 1 .. 5 -> $k { say ~.[^10] given grep { is-k-almost-prime($_, $k) }, 2 .. * }
Give a code snippet in #Raku 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,   whe...
christopher/rosetta-code
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#BBC_BASIC
BBC BASIC
10 MODE 1: REM 320x256 4 colour graphics
Give a code snippet in #BBC_BASIC The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#Factor
Factor
USING: io kernel math math.primes.factors prettyprint sequences ;   : next ( n num -- n' num' ) [ 2dup divisors length = ] [ 1 + ] do until [ 1 + ] dip ;   : A069654 ( n -- seq ) [ 2 1 ] dip [ [ next ] keep ] replicate 2nip ;   "The first 15 terms of the sequence are:" print 15 A069654 .
Give a code snippet in #Factor Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Fortran
Fortran
  program anti_primes use iso_fortran_env, only: output_unit implicit none   integer :: n, d, maxDiv, pCount   write(output_unit,*) "The first 20 anti-primes are:" n = 1 maxDiv = 0 pCount = 0 do if (pCount >= 20) exit   d = countDivisors(n) if (d > maxDiv) then ...
Give a code snippet in #Fortran The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#zkl
zkl
class MagicSquareSinglyEven{ fcn init(n){ var result=magicSquareSinglyEven(n) } fcn toString{ sink,n:=Sink(String),result.len(); // num collumns fmt:="%2s "; foreach row in (result) { sink.write(row.apply('wrap(n){ fmt.fmt(n) }).concat(),"\n") } sink.write("\nMagic constant: %d"....
Give a code snippet in #zkl A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a m...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Julia
Julia
function writeFile(filename, data) f = open(filename, "w") write(f, data) close(f) end   writeFile("test.txt", "Hi there.")
Give a code snippet in #Julia Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
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 |...
#ARM_Assembly
ARM Assembly
;this example uses VASM syntax, your assembler may not use the # before constants or the semicolon for comments MOV R1,#0x04000000 MOV R0,#0x403 STR R0,[R1] ;store 0x403 into memory address 0x04000000.
Give a code snippet in #ARM_Assembly Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#RPGIV
RPGIV
  dcl-c DIVIDE_BY_ZERO 00102;   dcl-s result zoned(5:2); dcl-s value1 zoned(5:2); dcl-s value2 zoned(5:2);   value1 = 10; value2 = 0;   monitor; eval(h) result = value1 / value2; // Using half rounding here for the eval result on-error DIVIDE_BY_ZERO; ...
Give a code snippet in #RPGIV Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/The_ISAAC_Cipher
The ISAAC Cipher
ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming...
#Tcl
Tcl
package require Tcl 8.6   oo::class create ISAAC { variable aa bb cc mm randrsl randcnt   constructor {seed} { namespace eval tcl { namespace eval mathfunc { proc mm {idx} { upvar 1 mm list lindex $list [expr {$idx % [llength $list]}] } proc clamp {value} { expr {$value & 0xFFFFFFF...
Give a code snippet in #Tcl ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectu...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Corescript
Corescript
print Fibonacci Sequence: var previous = 1 var number = 0 var temp = (blank)   :fib if number > 50000000000:kill print (number) set temp = (add number previous) set previous = (number) set number = (temp) goto fib   :kill stop
Give a code snippet in #Corescript The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solution...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have m...
#Ruby
Ruby
Node = Struct.new(:val, :back)   def lis(n) pileTops = [] # sort into piles for x in n # binary search low, high = 0, pileTops.size-1 while low <= high mid = low + (high - low) / 2 if pileTops[mid].val >= x high = mid - 1 else low = mid + 1 end end i = l...
Give a code snippet in #Ruby Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#JavaScript
JavaScript
function distcheck(random_func, times, opts) { if (opts === undefined) opts = {} opts['delta'] = opts['delta'] || 2;   var count = {}, vals = []; for (var i = 0; i < times; i++) { var val = random_func(); if (! has_property(count, val)) { count[val] = 1; vals.push...
Give a code snippet in #JavaScript This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing ra...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe
Bitmap/Read an image through a pipe
This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PP...
#OCaml
OCaml
let read_image ~filename = if not(Sys.file_exists filename) then failwith(Printf.sprintf "the file %s does not exist" filename); let cmd = Printf.sprintf "convert \"%s\" ppm:-" filename in let ic, oc = Unix.open_process cmd in let img = read_ppm ~ic in (img) ;;
Give a code snippet in #OCaml This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Scheme
Scheme
  (define (square n) (* n n))   (define (mod-exp a n mod) (cond ((= n 0) 1) ((even? n) (remainder (square (mod-exp a (/ n 2) mod)) mod)) (else (remainder (* a (mod-exp a (- n 1) mod)) mod))))   (define result (mod-exp 29883481620585741369158...
Give a code snippet in #Scheme Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Z80_Assembly
Z80 Assembly
BIT 0,A jr nz,true ;;;;;;;;;;;;;;;; AND 1 jr nz,true ;;;;;;;;;;;;;;;; RRCA jr c,true
Give a code snippet in #Z80_Assembly Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code