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/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#MATLAB_.2F_Octave
MATLAB / Octave
n = 15; p = pascal(n + 2); p(n + 4 : n + 3 : end - 1)' - diag(p, 2)
Give a code snippet in #MATLAB_.2F_Octave Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triang...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Tcl
Tcl
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc gcd_iter {p q} { while {$q != 0} { lassign [list $q [% $p $q]] p q } abs $p }
Give a code snippet in #Tcl Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest c...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list 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 list: Element definition, Element insertion, Lis...
#Delphi
Delphi
Type pOneWayList = ^OneWayList; OneWayList = record pData : pointer ; Next : pOneWayList ; end;
Give a code snippet in #Delphi singly-linked list 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 list: Element de...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Nim
Nim
import strutils   for i in 0..33: echo toBin(i, 6)," ",toOct(i, 3)," ",align($i,2)," ",toHex(i,2)
Give a code snippet in #Nim Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routi...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#VBA
VBA
Public Sub LoopsBreak() Dim value As Integer Randomize Do While True value = Int(20 * Rnd) Debug.Print value If value = 10 Then Exit Do Debug.Print Int(20 * Rnd) Loop End Sub
Give a code snippet in #VBA Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Wren
Wren
import "/fmt" for Fmt   var ncs = Fn.new { |a| var f = "$d " if (a[0] is String) { for (i in 0...a.count) a[i] = a[i].bytes[0] f = "$c " } var generate // recursive generate = Fn.new { |m, k, c| if (k == m) { if (c[m - 1] != c[0] + m - 1) { for (i ...
Give a code snippet in #Wren Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#NewLISP
NewLISP
(dup "ha" 5)
Give a code snippet in #NewLISP Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Lua
Lua
local csv={} for line in io.lines('file.csv') do table.insert(csv, {}) local i=1 for j=1,#line do if line:sub(j,j) == ',' then table.insert(csv[#csv], line:sub(i,j-1)) i=j+1 end end table.insert(csv[#csv], line:sub(i,j)) end   table.insert(csv[1], 'SUM') for i...
Give a code snippet in #Lua CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (load "@lib/misc.l" "@lib/gcc.l")   (gcc "x11" '("-lX11") 'simpleWin)   #include <X11/Xlib.h>   any simpleWin(any ex) { any x = cdr(ex); int dx, dy; Display *disp; int scrn; Window win; XEvent ev;   x = cdr(ex), dx = (int)evCnt(ex,x); x = cdr(x), d...
Give a code snippet in #PicoLisp Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Groovy
Groovy
  @Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1') import groovyx.gpars.GParsPool   GParsPool.withPool args.size(), { args.eachParallel { sleep(it.toInteger() * 10) println it } }  
Give a code snippet in #Groovy 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/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#Java
Java
  import java.util.Arrays;   public class MianChowlaSequence {   public static void main(String[] args) { long start = System.currentTimeMillis(); System.out.println("First 30 terms of the Mian–Chowla sequence."); mianChowla(1, 30); System.out.println("Terms 91 through 100 of the Mia...
Give a code snippet in #Java The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise...
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...
#BASIC
BASIC
  10 REM Horizontal sundial calculations 20 DEF FNM(X) = INT(X*1000+0.5)/1000 30 PRINT "Enter latitude"; 40 INPUT L 50 PRINT "Enter longitude"; 60 INPUT L1 70 PRINT "Enter legal meridian"; 80 INPUT R 90 PRINT 100 LET P = 4*ATN(1) 110 LET S1 = SIN(L*P/180) 120 PRINT " sine of latitude:"; S1 130 PRINT " diff longit...
Give a code snippet in #BASIC 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/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Latitude
Latitude
arr := n times to (Array) map { Object clone. }.
Give a code snippet in #Latitude Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are consi...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Clojure
Clojure
  (defn fib [] (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))   (time (take 100 (fib)))  
Give a code snippet in #Clojure Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time betwe...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation....
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On   Imports System.Text.RegularExpressions   Module Module1   Class Operator_ Sub New(t As Char, p As Integer, Optional i As Boolean = False) Token = t Precedence = p IsRightAssociative = i End Sub   Property Token As Char Get ...
Give a code snippet in #Visual_Basic_.NET Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#AWK
AWK
BEGIN { s="/inet/tcp/256/0/0" print strftime() |& s close(s) }  
Give a code snippet in #AWK For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#Haskell
Haskell
import Text.Printf (printf) import Data.List (unfoldr) import Control.Monad (guard)   factorion :: Int -> Int -> Bool factorion b n = f b n == n where f b = sum . map (product . enumFromTo 1) . unfoldr (\x -> guard (x > 0) >> pure (x `mod` b, x `div` b))   main :: IO () main = mapM_ (uncurry (printf "Factorions for ...
Give a code snippet in #Haskell Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes s...
#Go
Go
package main   import ( "fmt" "math" )   type Splitmix64 struct{ state uint64 }   func Splitmix64New(state uint64) *Splitmix64 { return &Splitmix64{state} }   func (sm64 *Splitmix64) nextInt() uint64 { sm64.state += 0x9e3779b97f4a7c15 z := sm64.state z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 z = ...
Give a code snippet in #Go Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many rand...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Sidef
Sidef
var a = [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_95097, 0.0...
Give a code snippet in #Sidef Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/lib...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Nim
Nim
import algorithm, sequtils, strutils   type OID = distinct string   # Borrow the `$` procedure from the base string type. proc `$`(oid: OID): string {.borrow.}     template toSeqInt(oid: OID): seq[int] = ## Convert an OID into a sequence of integers. oid.string.split('.').map(parseInt)     proc oidCmp(a, b: OID): i...
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/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub proc() Print " proc called" End Sub   Sub repeat(s As Sub, n As UInteger) For i As Integer = 1 To n Print Using "##"; i; s() Next End Sub   repeat(@proc, 5) Print Print "Press any key to quit" Sleep
Give a code snippet in #FreeBASIC Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#ML.2FI
ML/I
MCSKIP "WITH" NL "" Special variables "" There are four different kinds of variables in ML/I. "" Permanent (P) variables - these have no special predefined values. "" Character (C) variables - these have no special predefined values. "" Temporary (T) variables - a macro has at least three of these, and "" those have...
Give a code snippet in #ML.2FI Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Racket
Racket
#lang racket ;;; reads a licence file on standard input ;;; returns max licences used and list of times this occurred (define (count-licences) (let inner ((ln (read-line)) (in-use 0) (max-in-use 0) (times-list null)) (if (eof-object? ln) (values max-in-use (reverse times-list)) (let ((mtch (regex...
Give a code snippet in #Racket A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a ch...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes s...
#Factor
Factor
USING: io kernel math math.bitwise math.functions math.statistics namespaces prettyprint sequences ;   SYMBOL: state   : seed ( n -- ) 64 bits state set ;   : next-int ( -- n ) 0x9e3779b97f4a7c15 state [ + 64 bits ] change state get -30 0xbf58476d1ce4e5b9 -27 0x94d049bb133111eb -31 1 [ [ dupd shift bitxor ]...
Give a code snippet in #Factor Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Pascal
Pascal
Program Sockets_ExampleA;   Uses { Free Pascal RTL sockets unit } sockets;   Var TCP_Sock: integer; Remote_Addr: TSockAddr;   Message: string; PMessage: Pchar; Message_Len: integer;     Begin { Fill the record (struct) with the server's address information } With Remote_Addr do begin S...
Give a code snippet in #Pascal For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Ruby
Ruby
fusc = Enumerator.new do |y| y << 0 y << 1 arr = [0,1] 2.step do |n| res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2] y << res arr << res end end   fusc_max_digits = Enumerator.new do |y| cur_max, cur_exp = 0, 0 0.step do |i| f = fusc.next if f >= cur_max cur_exp ...
Give a code snippet in #Ruby Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition sta...
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,...
#PicoLisp
PicoLisp
(setq A '((1 2 3) (a b c) ((d e) NIL 777))) # Create a 3x3 structure (mapc println A) # Show it
Give a code snippet in #PicoLisp 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 re...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#R
R
reversalGame <- function(){ cat("Welcome to the Number Reversal Game! \n") cat("Sort the numbers into ascending order by repeatedly \n", "reversing the first n digits, where you specify n. \n \n", sep="")   # Generate a list that's definitely not in ascending order, per instuctions data <- sample(1:9, 9) ...
Give a code snippet in #R Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#Phix
Phix
-- -- demo\rosetta\Sutherland_Hodgman_polygon_clipping.exw -- ==================================================== -- with javascript_semantics enum X,Y function inside(sequence cp1, cp2, p) return (cp2[X]-cp1[X])*(p[Y]-cp1[Y])>(cp2[Y]-cp1[Y])*(p[X]-cp1[X]) end function function intersect(sequence cp1, cp2, s, e)...
Give a code snippet in #Phix The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#Maple
Maple
  with(ArrayTools):   module Point() option object; local x := 0; local y := 0;   export getX::static := proc(self::Point, $) return self:-x; end proc;   export getY::static := proc(self::Point, $) return self:-y end proc;   export ModuleApply::static := proc() Object(Point, _passed); end proc;   export...
Give a code snippet in #Maple Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns th...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Visual_Basic_.NET
Visual Basic .NET
Module System_Command   Sub Main() Dim cmd As New Process cmd.StartInfo.FileName = "cmd.exe" cmd.StartInfo.RedirectStandardInput = True cmd.StartInfo.RedirectStandardOutput = True cmd.StartInfo.CreateNoWindow = True cmd.StartInfo.UseShellExecute = False   cmd....
Give a code snippet in #Visual_Basic_.NET Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#PicoLisp
PicoLisp
(de elementWiseMatrix (Fun Mat1 Mat2) (mapcar '((L1 L2) (mapcar Fun L1 L2)) Mat1 Mat2) )   (de elementWiseScalar (Fun Mat Scalar) (elementWiseMatrix Fun Mat (circ (circ Scalar))) )
Give a code snippet in #PicoLisp This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#AutoIt
AutoIt
  ConsoleWrite(Fibonacci(10) & @CRLF) ; ## USAGE EXAMPLE ConsoleWrite(Fibonacci(20) & @CRLF) ; ## USAGE EXAMPLE ConsoleWrite(Fibonacci(30)) ; ## USAGE EXAMPLE   Func Fibonacci($number)   If $number < 0 Then Return "Invalid argument" ; No negative numbers   If $number < 2 Then ; If $n...
Give a code snippet in #AutoIt While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwan...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Pascal
Pascal
program Sierpinski;   function ipow(b, n : Integer) : Integer; var i : Integer; begin ipow := 1; for i := 1 to n do ipow := ipow * b end;   function truth(a : Char) : Boolean; begin if a = '*' then truth := true else truth := false end;
Give a code snippet in #Pascal Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#Elixir
Elixir
defmodule RC do def largest_int(list) do sorted = Enum.sort(list, fn x,y -> "#{x}#{y}" >= "#{y}#{x}" end) Enum.join(sorted) end end   IO.inspect RC.largest_int [1, 34, 3, 98, 9, 76, 45, 4] IO.inspect RC.largest_int [54, 546, 548, 60]
Give a code snippet in #Elixir Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, ...
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
#Programming_Language
Programming Language
print(Hello world!)
Give a code snippet in #Programming_Language 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/S...
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...
#BBC_BASIC
BBC BASIC
DIM a(2), b(2), c(2), d(2) a() = 3, 4, 5 b() = 4, 3, 5 c() = -5, -12, -13   PRINT "a . b = "; FNdot(a(),b()) PROCcross(a(),b(),d()) PRINT "a x b = (";d(0)", ";d(1)", ";d(2)")" PRINT "a . (b x c) = "; FNscalartriple(a(),b(),c()) PROCvectortriple(a(),b(),c(),d()) ...
Give a code snippet in #BBC_BASIC 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext...
#Ruby
Ruby
  #!/usr/bin/ruby   bpm = Integer(ARGV[0]) rescue 60 # sets BPM by the first command line argument, set to 60 if none provided msr = Integer(ARGV[1]) rescue 4 # sets number of beats in a measure by the second command line argument, set to 4 if none provided i = 0   loop do (msr-1).times do puts "\a" sleep(60...
Give a code snippet in #Ruby The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Creative_Basic
Creative Basic
  == Get ==   To get the address of a variable without using the Windows API:   DEF X:INT DEF pPointer:POINTER pPointer=X   ----   To get the address of a variable using the Windows API Lstrcpy function called in Creative Basic: (This may give users of another language without a native way to get the address of a varia...
Give a code snippet in #Creative_Basic 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 Op...
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...
#Ruby
Ruby
$cache = {} def selfReferentialSequence_cached(n, seen = []) return $cache[n] if $cache.include? n return [] if seen.include? n   digit_count = Array.new(10, 0) n.to_s.chars.collect {|char| digit_count[char.to_i] += 1} term = '' 9.downto(0).each do |d| if digit_count[d] > 0 term += digit_count[d]....
Give a code snippet in #Ruby 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, 31131...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Racket
Racket
#lang racket/base (require 2htdp/universe 2htdp/image racket/list racket/match)   (define ((fifteen->pict (finished? #f)) fifteen) (for/fold ((i (empty-scene 0 0))) ((r 4)) (define row (for/fold ((i (empty-scene 0 0))) ((c 4)) (define v (list-ref fifteen (+ (* r 4) c))) (define cell ...
Give a code snippet in #Racket Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Java
Java
import java.util.concurrent.CyclicBarrier;   public class Threads { public static class DelayedMessagePrinter implements Runnable { private CyclicBarrier barrier; private String msg;   public DelayedMessagePrinter(CyclicBarrier barrier, String msg) { this.barrier = barrier; this.msg = ms...
Give a code snippet in #Java Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your la...
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
#Ring
Ring
  x = True y = False see "x and y : " + (x and y) + nl see "x or y : " + (x or y) + nl see "not x : " + (not x) + nl  
Give a code snippet in #Ring Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Rust
Rust
use std::io; use std::io::BufRead;   fn parse_entry(l: &str) -> (i32, String) { let params: Vec<&str> = l.split(' ').collect();   let divisor = params[0].parse::<i32>().unwrap(); let word = params[1].to_string(); (divisor, word) }   fn main() { let stdin = io::stdin(); let mut lines = stdin.lock...
Give a code snippet in #Rust Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with...
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      ...
#NS-HUBASIC
NS-HUBASIC
10 LIST
Give a code snippet in #NS-HUBASIC 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 progr...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Ruby
Ruby
str = "I am a string" p "Ends with 'string'" if str =~ /string$/ p "Does not start with 'You'" unless str =~ /^You/
Give a code snippet in #Ruby Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Prolog
Prolog
a_to_z(From, To, L) :- maplist(atom_codes, [From, To], [[C_From], [C_To]]), bagof([C], between(C_From, C_To, C), L1), maplist(atom_codes,L, L1).  
Give a code snippet in #Prolog Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Windows.Forms   Module GoodbyeWorld Sub Main() Messagebox.Show("Goodbye, World!") End Sub End Module
Give a code snippet in #Visual_Basic_.NET Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
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...
#ALGOL_68
ALGOL 68
PRAGMAT precision=200 PRAGMAT MODE INTEGER = LONG LONG INT;   LONG INT default integer width := 69; INT width = 69+2;   INT fix w = 1, fix h = 1; # round up #   LONG LONG INT golden ratio w := ENTIER ((long long sqrt(5)-1) / 2 * LENG LENG 10 ** default integer width + fix w), golden ratio h := ENTIER ((lo...
Give a code snippet in #ALGOL_68 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#C
C
#include <stdio.h> #include <stdlib.h> // atoi() #include <math.h> // pow()   int main(int argc, char* argv[]) { int i, count=0; double f, sum=0.0, prod=1.0, resum=0.0;   for (i=1; i<argc; ++i) { f = atof(argv[i]); count++; sum += f; prod *= f; resum += (1.0/f); } //printf(" c:%d\n s:%f\n ...
Give a code snippet in #C Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Raku
Raku
 
Give a code snippet in #Raku Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#J
J
mean=: +/ % # dev=: - mean stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP stddevP=: [: mean&.:*: dev NB. B) uses Under (&.:) to apply inverse of *: after mean stddevP=: %:@(mean@:*: - *:@mean) NB. C) sqrt of ((mean of squares) - (square of mean))     stddevP\ 2 ...
Give a code snippet in #J Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Rust
Rust
use url::Url;   fn print_fields(url: Url) -> () { println!("scheme: {}", url.scheme()); println!("username: {}", url.username());   if let Some(password) = url.password() { println!("password: {}", password); }   if let Some(domain) = url.domain() { println!("domain: {}", domain); ...
Give a code snippet in #Rust URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. ...
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...
#Stata
Stata
forvalues i=1(2)10 { display "`i'" }   1 3 5 7 9
Give a code snippet in #Stata 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/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#M4
M4
define(`ack',`ifelse($1,0,`incr($2)',`ifelse($2,0,`ack(decr($1),1)',`ack(decr($1),ack($1,decr($2)))')')')dnl ack(3,3)
Give a code snippet in #M4 The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Delphi.2FPascal
Delphi/Pascal
var matrix: array[1..10,1..10] of Integer; row, col: Integer; broken: Boolean; begin // Launch random number generator randomize; // Filling matrix with random numbers for row := 1 to 10 do for col := 1 to 10 do matrix[row, col] := Succ(Random(20)); // Displaying values one by one, until at th...
Give a code snippet in #Delphi.2FPascal Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Prolog
Prolog
  :- initialization(main).   vector_plus(U, V, W) :- U = p(X1, Y1, Z1), V = p(X2, Y2, Z2), X3 is X1 + X2, Y3 is Y1 + Y2, Z3 is Z1 + Z2, W = p(X3, Y3, Z3).   vector_minus(U, V, W) :- U = p(X1, Y1, Z1), V = p(X2, Y2, Z2), X3 is X1 - X2, Y3 is Y1 - Y2, Z3 is Z1 - Z2, W = p(X...
Give a code snippet in #Prolog Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of...
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...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { for (i in 1 .. 21 step 2) print("$i ") }
Give a code snippet in #Kotlin 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/In...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#11l
11l
F pdsum(n) R sum((1 .. (n + 1) I/ 2).filter(x -> @n % x == 0 & @n != x))   F aliquot(n, maxlen = 16, maxterm = 2 ^ 30) I n == 0 R (‘terminating’, [0]) V s = [n] V slen = 1 V new = n L slen <= maxlen & new < maxterm new = pdsum(s.last) I new C s I s[0] == new I sl...
Give a code snippet in #11l An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications f...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Sparkling
Sparkling
let a = 13, b = 37; if a < b { print("a < b"); } else if a > b { print("a > b"); } else if a == b { print("a == b"); } else { print("either a or b or both are NaN"); }
Give a code snippet in #Sparkling Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#MiniScript
MiniScript
zeta = function(num) return 1 / num^2 end function   sum = function(start, finish, formula) total = 0 for i in range(start, finish) total = total + formula(i) end for return total end function   print sum(1, 1000, @zeta)  
Give a code snippet in #MiniScript 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 = ∑ ...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#HicEst
HicEst
OPEN(FIle= 'input.txt', OLD, IOStat=ios, ERror=99) OPEN(FIle='C:\input.txt', OLD, IOStat=ios, ERror=99) ! ... 99 WRITE(Messagebox='!') 'File does not exist. Error message ', ios
Give a code snippet in #HicEst Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works wi...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Frink
Frink
  a = "alphaBETA" println[lc[a]] println[uc[a]]  
Give a code snippet in #Frink Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not r...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#IS-BASIC
IS-BASIC
100 PROGRAM "Coins.bas" 110 LET MONEY=100 120 LET COUNT=0 125 PRINT "Count Pennies Nickles Dimes Quaters" 130 FOR QC=0 TO INT(MONEY/25) 150 FOR DC=0 TO INT((MONEY-QC*25)/10) 170 FOR NC=0 TO INT((MONEY-DC*10)/5) 190 FOR PC=0 TO MONEY-NC*5 STEP 5 200 LET S=PC+NC*5+DC*10+QC*25 210 IF S=MONEY T...
Give a code snippet in #IS-BASIC There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels an...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Ruby
Ruby
def deranged?(a, b) a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b} end   def find_derangements(list) list.combination(2) {|a,b| return a,b if deranged?(a,b)} nil end   require 'open-uri' anagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f| f.read.split.group_by {|s| s.each...
Give a code snippet in #Ruby Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#LiveCode
LiveCode
command shaRosettaCode local shex, sha1 put sha1Digest("Rosetta Code") into sha1 get binaryDecode("H*",sha1,shex) put shex end shaRosettaCode
Give a code snippet in #LiveCode SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#Nim
Nim
import math, random, sequtils, stats, strformat, strutils   proc drawHistogram(ns: seq[float]) =   # Distribute values in bins. const NBins = 50 var minval = min(ns) var maxval = max(ns) var h = newSeq[int](NBins + 1) for n in ns: let pos = ((n - minval) * NBins / (maxval - minval)).toInt inc h[pos]...
Give a code snippet in #Nim The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random n...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#LiveCode
LiveCode
function rlEncode str local charCount put 1 into charCount repeat with i = 1 to the length of str if char i of str = char (i + 1) of str then add 1 to charCount else put char i of str & charCount after rle put 1 into charCount end if end repeat...
Give a code snippet in #LiveCode Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a f...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Wortel
Wortel
@uniq [1 2 3 2 1 2 3] ; returns [1 2 3]
Give a code snippet in #Wortel 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/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Python
Python
inclusive_range = mn, mx = (1, 10)   print('''\ Think of a number between %i and %i and wait for me to guess it. On every guess of mine you should state whether the guess was too high, too low, or equal to your number by typing h, l, or = ''' % inclusive_range)   i = 0 while True: i += 1 guess = (mn+mx)//2 ...
Give a code snippet in #Python Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Bracmat
Bracmat
@("fesylk789/35768poq2art":? (#<7:?n & out$!n & ~) ?)
Give a code snippet in #Bracmat Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Elixir
Elixir
defmodule RC do def entropy(str) do leng = String.length(str) String.graphemes(str) |> Enum.group_by(&(&1)) |> Enum.map(fn{_,value} -> length(value) end) |> Enum.reduce(0, fn count, entropy -> freq = count / leng entropy - freq * :math.log2(freq) end) end end   IO.inspec...
Give a code snippet in #Elixir Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary),...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclotomic_polynomial
Cyclotomic polynomial
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and print the order of the first 10...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <initializer_list> #include <map> #include <vector>   const int MAX_ALL_FACTORS = 100000; const int algorithm = 2; int divisions = 0;   //Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage. class Term { private: long ...
Give a code snippet in #C.2B.2B The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find an...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Groovy
Groovy
def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() } def missingPerms missingPerms = {List elts, List perms -> perms.empty ? elts.permutations() : elts.collect { e -> def ePerms = perms.findAll { e == it[0] }.collect { it[1..-1] } ePerms.size() == fact(elts.size() - 1) ? [] \ ...
Give a code snippet in #Groovy ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
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...
#EchoLisp
EchoLisp
  ;; copied from Racket   (for*/list ([x (in-range 1 21)] [y (in-range x 21)] [z (in-range y 21)]) #:when (= (+ (* x x) (* y y)) (* z z)) (list x y z)) → ((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))  
Give a code snippet in #EchoLisp 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#J
J
  NB. monad implementation: unit=: < bind=: (@>)( :: ])   NB. monad utility safeVersion=: (<@) ( ::((<_.)"_)) safeCompose=:dyad define dyad def 'x`:6 bind y'/x,unit y )   NB. unsafe functions (fail with infinite arguments) subtractFromSelf=: -~ divideBySelf=: %~   NB. wrapped functions: safeSubtractFromSelf=: subtrac...
Give a code snippet in #J Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return ...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#COBOL
COBOL
  identification division. program-id. split-ch. data division. 1 split-str pic x(30) value space. 88 str-1 value "gHHH5YY++///\". 88 str-2 value "gHHH5 ))YY++,,,///\". 1 binary. 2 ptr pic 9(4) value 1. 2 str-start pic 9(4) value 1. 2 delim-len p...
Give a code snippet in #COBOL Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   Th...
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
#Python
Python
print "Hello world!"
Give a code snippet in #Python Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Fortran
Fortran
module subgenerator implicit none   integer, parameter :: modulus = 1000000000 integer :: s(0:54), r(0:54)   contains   subroutine initgen(seed) integer :: seed integer :: n, rnum   s(0) = seed s(1) = 1   do n = 2, 54 s(n) = mod(s(n-2) - s(n-1), modulus) if (s(n) < 0) s(n) = s(n) + modulus en...
Give a code snippet in #Fortran 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/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Forth
Forth
CREATE BUF 0 , : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : >Integer >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ; : SKIP ( xt --) B...
Give a code snippet in #Forth A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
locs = Position[ ImageData[Binarize[Rasterize["Mathematica", ImageSize -> 150]]], 0]; Print[StringRiffle[ StringJoin /@ ReplacePart[ ReplacePart[ ConstantArray[ " ", {Max[locs[[All, 1]]] + 1, Max[locs[[All, 2]]] + 1}], locs -> "\\"], Map[# + 1 &, locs, {2}] -> "#"], "\n"]];
Give a code snippet in #Mathematica.2FWolfram_Language Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube d...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Groovy
Groovy
def sha256Hash = { text -> java.security.MessageDigest.getInstance("SHA-256").digest(text.bytes) .collect { String.format("%02x", it) }.join('') }
Give a code snippet in #Groovy SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b7...
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...
#AutoHotkey
AutoHotkey
;========================================================== ; create cards cards := [], suits := ["♠","♥","♦","♣"], num := 0 for i, v in StrSplit("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") for i, suit in suits cards[++num] := v suit ;========================================================== ; create gui w := 40 Gui, font, S...
Give a code snippet in #AutoHotkey 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 simula...
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 ...
#Ursala
Ursala
#import std #import nat   prime = ~<{0,1}&& -={2,3}!| ~&h&& (all remainder)^Dtt/~& iota@K31
Give a code snippet in #Ursala 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 loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#S-lang
S-lang
variable old = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; variable new = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";   define rot13(s) { s = strtrans(s, old, new); return s; }   define rot13_stream(s) { variable ln; while (-1 != fgets(&ln, s)) fputs(rot13(ln), stdout); }   if (__arg...
Give a code snippet in #S-lang Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-1...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#zkl
zkl
class C{var v; fcn f{v}} C.f() // call function f in class C C.v=5; c2:=C(); // create new instance of C println(C.f()," ",c2.f()) //-->5 Void C.f.isStatic //--> False   class [static] D{var v=123; fcn f{v}} D.f(); D().f(); // both return 123 D.f.isStatic //-->False   class E{var v; fcn f{}} E.f.isStatic //-->True
Give a code snippet in #zkl In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or cl...
christopher/rosetta-code
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table
Display an outline as a nested table
Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. defining the width of a ...
#AutoHotkey
AutoHotkey
outline2table(db, Delim:= "`t"){ oNum:=[], oMID:=[], oNod := [], oKid := [], oPnt := [], oMbr := [], oLvl := [] oCrl := ["#ffffe6;", "#ffebd2;", "#f0fff0;", "#e6ffff;", "#ffeeff;"] col := 0, out := "", anc := ""   ; create numerical index for each line for i, line in StrSplit(db, "`n", "`r") { RegExMatch(line, ...
Give a code snippet in #AutoHotkey Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to ev...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Lingo
Lingo
-- load Lingo code from file fp = xtra("fileIO").new() fp.openFile(_movie.path&"someinclude.ls", 1) code = fp.readFile() fp.closeFile()   -- create new script member, assign loaded code m = new(#script) m.name = "someinclude" m.scriptText = code   -- use it instantly in the current script (i.e. the script that containe...
Give a code snippet in #Lingo Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#Rust
Rust
extern crate csv; extern crate getopts; extern crate gnuplot; extern crate nalgebra; extern crate num; extern crate rand; extern crate rustc_serialize; extern crate test;   use getopts::Options; use gnuplot::{Axes2D, AxesCommon, Color, Figure, Fix, PointSize, PointSymbol}; use nalgebra::{DVector, Iterable}; use rand::{...
Give a code snippet in #Rust K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the datase...
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Scala
Scala
import scala.actors.Futures List("Enjoy", "Rosetta", "Code").map { x => Futures.future { Thread.sleep((Math.random * 1000).toInt) println(x) } }.foreach(_())
Give a code snippet in #Scala Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your l...
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 ...
#BASIC
BASIC
  10 'SAVE"SELSORT",A 20 ' Selection Sort Algorithm 30 ' 40 ' VAR 50 DEFINT A-Z 60 OPTION BASE 1 70 I=0: J=0: IMINV = 0: IMAX = 0: TP! = 0: TL! = 0 80 ' 90 CLS 100 PRINT "This program does the Selection Sort Algorithm" 110 INPUT "Number of elements to sort (Max=1000, Enter=10)";IMAX 120 IF IMAX = 0 THEN IMAX = 10 130 I...
Give a code snippet in #BASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Run_BASIC
Run BASIC
a$ = "2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2"   for i = 1 to len(a$) a1$ = word$(a$,i) if a1$ = "" then exit for for i1 = 1 to len(b$) if a1$ = word$(b$,i1) then [nextWord] next i1 b$ = b$ + a1$ + " " [nextWord] next i   print "Dups:";a$ print "No Dups:";b$
Give a code snippet in #Run_BASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Groovy
Groovy
def notes = new File('./notes.txt') if (args) { notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n" } else { println notes.text }  
Give a code snippet in #Groovy Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TX...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Kotlin
Kotlin
// version 1.1   import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.*   class Cuboid: JPanel() { private val nodes = arrayOf( doubleArrayOf(-1.0, -1.0, -1.0), doubleArrayOf(-1.0, -1.0, 1.0), doubleArrayOf(-1.0, 1.0, -1.0), doubl...
Give a code snippet in #Kotlin Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection i...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Modula-3
Modula-3
MODULE EnvVars EXPORTS Main;   IMPORT IO, Env;   VAR k, v: TEXT;   BEGIN IO.Put(Env.Get("HOME") & "\n");   FOR i := 0 TO Env.Count - 1 DO Env.GetNth(i, k, v); IO.Put(k & " = " & v & "\n") END END EnvVars.
Give a code snippet in #Modula-3 Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Lasso
Lasso
define stat1(a) => { if(#a->size) => { local(mean = (with n in #a sum #n) / #a->size) local(sdev = math_pow(((with n in #a sum Math_Pow((#n - #mean),2)) / #a->size),0.5)) return (:#sdev, #mean) else return (:0,0) } } define stat2(a) => { if(#a->size) => { local(sx = 0, sxx = 0) with x in #a do => { #...
Give a code snippet in #Lasso Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Factor
Factor
USING: formatting fry kernel lists lists.lazy locals math.combinatorics math.primes.factors math.ranges sequences ; IN: rosetta-code.almost-prime   : k-almost-prime? ( n k -- ? ) '[ factors _ <combinations> [ product ] map ] [ [ = ] curry ] bi any? ;   :: first10 ( k -- seq ) 10 0 lfrom [ k k-almost-prime? ...
Give a code snippet in #Factor 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/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#11l
11l
V y = String(BigInt(5) ^ 4 ^ 3 ^ 2) print(‘5^4^3^2 = #....#. and has #. digits’.format(y[0.<20], y[(len)-20..], y.len))
Give a code snippet in #11l Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Vlang
Vlang
import ui   fn main() { ui.message_box('Hello World') }
Give a code snippet in #Vlang Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Run_BASIC
Run BASIC
dim choose$(5) choose$(1) = "1 Fee Fie" choose$(2) = "2 Huff Puff" choose$(3) = "3 Mirror, Mirror" choose$(4) = "4 Tick, Tock" choose$(5) = "Exit"   [start] print "Menu Selection" listbox #lb,choose$(),5 button #sel, "Accept",[select] wait   [select] selected$=#lb selection$() print " " if selected$<>"" then print "Y...
Give a code snippet in #Run_BASIC Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the ...
christopher/rosetta-code