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/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh";   sub MakeList(sep: [uint8], buf: [uint8]): (out: [uint8]) is out := buf; # return begin of buffer for ease of use var counter: uint32 := 0;   # Add item to string sub AddStr(str: [uint8]) is var length := StrLen(str); MemCopy(str, length, buf...
Give a code snippet in #Cowgol In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of tw...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#F.23
F#
let mode (l:'a seq) = l |> Seq.countBy (fun item -> item) // Count individual items |> Seq.fold // Find max counts (fun (cp, lst) (item, c) -> // State is (count, list of items with that count) if c > cp then (c, [item]) ...
Give a code snippet in #F.23 Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if pos...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#IDL
IDL
m=[[1,1,1,1],[2, 4, 8, 16],[3, 9,27, 81],[5, 25,125, 625]] print,transpose(m)
Give a code snippet in #IDL Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Oforth
Oforth
: topAndTail(s) s right(s size 1-) println s left(s size 1-) println s extract(2, s size 1- ) println ;
Give a code snippet in #Oforth The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Octave
Octave
sum(1 ./ [1:1000] .^ 2)
Give a code snippet in #Octave 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 = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#VBScript
VBScript
dim s s = createobject("scripting.filesystemobject").opentextfile("slurp.vbs",1).readall wscript.echo s
Give a code snippet in #VBScript Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished in...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Nim
Nim
import algorithm, htmlparser, httpclient, json import sequtils, strformat, strscans, tables, times, xmltree import strutils except escape   const   Rosorg = "http://rosettacode.org" QUri = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json" QdUri = "/mw/api.p...
Give a code snippet in #Nim Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Common_Lisp
Common Lisp
(let ((x 42)) (assert (and (integerp x) (= 42 x)) (x)))
Give a code snippet in #Common_Lisp Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#C.2B.2B
C++
#include <algorithm> #include <cctype> #include <string> #include <iostream>   const std::string alphabet("abcdefghijklmnopqrstuvwxyz");   bool is_pangram(std::string s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); std::sort(s.begin(), s.end()); return std::includes(s.begin(), s.end(), alphab...
Give a code snippet in #C.2B.2B Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task W...
christopher/rosetta-code
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#ATS
ATS
  (* ****** ****** *) // // This is a memory-clean implementation: // Every byte of allocated memory is freed // before the program exits. // (* ****** ****** *) // #include "share/atspre_define.hats" #include "share/atspre_staload.hats" // (* #include "share/HATS/atspre_staload_libats_ML.hats" *) // (* ****** ****** *...
Give a code snippet in #ATS 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which t...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Scala
Scala
println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.")
Give a code snippet in #Scala Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Tcl
Tcl
proc divCount {n} { set cnt 0 for {set d 1} {($d * $d) <= $n} {incr d} { if {0 == ($n % $d)} { incr cnt if {$d < ($n / $d)} { incr cnt } } } return $cnt }   proc A005179 {n} { if {$n >= 1} { for {set k 1} {1} {incr k} { ...
Give a code snippet in #Tcl Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#EchoLisp
EchoLisp
  (require 'struct) (require 'hash) (require 'sql) (require 'words) (require 'dico.fr.no-accent)     (define mots-français (words-select #:any null 999999)) (string-delimiter "")   (define (string-sort str) (list->string (list-sort string<? (string->list str))))   (define (ana-sort H words) ;; bump counter for each w...
Give a code snippet in #EchoLisp When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words i...
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...
#Phix
Phix
constant s = sq_rand(repeat(repeat(20,20),20)) integer found = 0 for i=1 to 20 do for j=1 to 20 do printf(1,"%d",s[i][j]) if s[i][j]=20 then found = 1 exit end if printf(1,", ") end for printf(1,"\n") if found then exit end if end for
Give a code snippet in #Phix 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#PARI.2FGP
PARI/GP
str = concat(apply(s->concat(s,"\n"), readstr("file.txt")))
Give a code snippet in #PARI.2FGP Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished i...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#PureBasic
PureBasic
Macro Assert(TEST,MSG="Assert: ") CompilerIf #PB_Compiler_Debugger If Not (TEST) Debug MSG+" Line="+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File CallDebugger EndIf CompilerEndIf EndMacro
Give a code snippet in #PureBasic Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#VBA
VBA
Type point x As Integer y As Integer End Type
Give a code snippet in #VBA Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Rel...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#SequenceL
SequenceL
  import <Utilities/Sequence.sl>; import <Utilities/Math.sl>;   main(args(2)) := LenenshteinDistance(args[1], args[2]);   LenenshteinDistance(s(1), t(1)) := 0 when equalList(s,t) else size(t) when size(s) = 0 else size(s) when size(t) = 0 else LenenshteinDistanceIterative(s, t, 0 ... size(t), duplicate(0, size(t) +...
Give a code snippet in #SequenceL This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#REXX
REXX
/*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */ parse arg N . /*Obtain the optional argument from CL.*/ if N=='' | N=="," then N=15 /*Not specified? Then use the default.*/ numeric digits max(9, N%2 + N%8) ...
Give a code snippet in #REXX 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 gener...
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...
#ColdFusion
ColdFusion
  <cfloop from="0" to="99" step="3" index="i"> <Cfoutput>#i#</Cfoutput> </cfloop>  
Give a code snippet in #ColdFusion 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   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coeffici...
#Kotlin
Kotlin
import java.math.BigInteger   fun main() { println("Unsigned Stirling numbers of the first kind:") val max = 12 print("n/k") for (n in 0..max) { print("%10d".format(n)) } println() for (n in 0..max) { print("%-3d".format(n)) for (k in 0..n) { print("%10s"....
Give a code snippet in #Kotlin Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#PL.2FI
PL/I
  Generate: procedure options (main); /* 27 October 2013 */ declare j fixed binary; declare r fixed binary;   /* Ignore the first 20 values */ do j = 1 to 20; /* put edit (filter() ) (f(6)); */ r = filter (); end; put skip; do j = 1 to 10; ...
Give a code snippet in #PL.2FI A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Tcl
Tcl
proc meanTime {times} { set secsPerRad [expr {60 * 60 * 12 / atan2(0,-1)}] set sumSin [set sumCos 0.0] foreach t $times { # Convert time to count of seconds from midnight scan $t "%02d:%02d:%02d" h m s incr s [expr {[incr m [expr {$h * 60}]] * 60}] # Feed into averaging set sumSin [expr {$sumSin + sin(...
Give a code snippet in #Tcl Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of...
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
#Clojure
Clojure
  (import '[java.util Date]) (import '[clojure.lang Reflector])   (def date1 (Date.)) (def date2 (Date.)) (def method "equals")   ;; Two ways of invoking method "equals" on object date1 ;; using date2 as argument   ;; Way 1 - Using Reflector class ;; NOTE: The argument date2 is passed inside an array (Reflector/invokeM...
Give a code snippet in #Clojure 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/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ByteCount["somerandomstring"]
Give a code snippet in #Mathematica.2FWolfram_Language Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Nim
Nim
import math   type Point = tuple[x,y,z: float]   const shades = ".:!*oe&#%@"   proc normalize(x, y, z: float): Point = let len = sqrt(x*x + y*y + z*z) (x / len, y / len, z / len)   proc dot(a, b: Point): float = result = max(0, - a.x*b.x - a.y*b.y - a.z*b.z)   let light = normalize(30.0, 30.0, -50.0)   proc drawS...
Give a code snippet in #Nim Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deat...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Sidef
Sidef
func lltp(n) { var b = 1 var best = nil var v = (n-1 -> primes)   while (v) { best = v.max b *= n v.map! { |vi| {|i| i*b + vi }.map(1..^n).grep{.is_prime}... } }   return best }   for i in (3..17) { printf("%2d %s\n", i, lltp(i)) }
Give a code snippet in #Sidef A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Liberty_BASIC
Liberty BASIC
  global tt$ tt$="-0+" '-1 0 1; +2 -> 1 2 3, instr   'Test case: 'With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-": '* write out a, b and c in decimal notation; '* calculate a * (b - c), write out the result in both ternary and decimal notations.   a$="+-0++0+" a=deci(a$) print "...
Give a code snippet in #Liberty_BASIC Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0...
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 |...
#QB64
QB64
  DefStr S DefInt P string2 = "dogs" string1 = "dogs and cats are often enemies,because dogs are stronger than cats, but cats sometimes can be friend to dogs" position = 0 pcount = 0 Print "Searching "; string2; " into "; string1 While (InStr(position, string1, string2) > 0) position = InStr(position + 1, string1, ...
Give a code snippet in #QB64 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Delphi
Delphi
  program Public_point_to_address;   {$APPTYPE CONSOLE}   uses System.SysUtils, Winapi.Windows, DCPsha256, DCPripemd160;   const bitcoinVersion = 0;   type TByteArray = array of Byte;   TA25 = TByteArray;   TPPoint = record x, y: TByteArray; constructor SetHex(xi, yi: ansistring); end;   TA2...
Give a code snippet in #Delphi Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in o...
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...
#Rust
Rust
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer};   fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?;   // headers() returns an immutable reference, so clone() before appending let mu...
Give a code snippet in #Rust 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, chang...
christopher/rosetta-code
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Julia
Julia
using Primes   function nsmooth(N, needed) nexts, smooths = [BigInt(i) for i in 2:N if isprime(i)], [BigInt(1)] prim, count = deepcopy(nexts), 1 indices = ones(Int, length(nexts)) while count < needed x = minimum(nexts) push!(smooths, x) count += 1 for j in 1:length(nexts...
Give a code snippet in #Julia n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Arturo
Arturo
dates: [ [May 15] [May 16] [May 19] [June 17] [June 18] [July 14] [July 16] [August 14] [August 15] [August 17] ]   print ["possible dates:" dates]   print "\n(1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too." print "\t-> meaning: the month cannot have a uniq...
Give a code snippet in #Arturo Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#R
R
  install.packages("audio") library(audio) hz=c(1635,1835,2060,2183,2450,2750,3087,3270) for (i in 1:8){ play(audioSample(sin(1:1000), hz[i])) Sys.sleep(.7) }  
Give a code snippet in #R Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#AmigaE
AmigaE
PROC main() IF ($2d7 = 727) AND (%001011010111 = 727) THEN WriteF('true\n') ENDPROC
Give a code snippet in #AmigaE Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should b...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#11l
11l
F one_of_n(lines) V choice = 0 L(line) lines I random:(0..L.index) == 0 choice = line R choice   F one_of_n_test(n = 10, trials = 1000000) V bins = [0] * n I n != 0 L 1..trials bins[one_of_n(0 .< n)]++ R bins   print(one_of_n_test())
Give a code snippet in #11l A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line ...
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Perl
Perl
use DBI;   my $db = DBI->connect('DBI:mysql:database:server','login','password');   my $statment = <<EOF; CREATE TABLE `Address` ( `addrID` int(11) NOT NULL auto_increment, `addrStreet` varchar(50) NOT NULL default '', `addrCity` varchar(25) NOT NULL default '', `addrState` char...
Give a code snippet in #Perl Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state cod...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#X86_Assembly
X86 Assembly
.model tiny .code .486 org 100h ;assume ax=0, bx=0, sp=-2 start: mov al, 13h ;(ah=0) set 320x200 video graphics mode int 10h push 0A000h pop es mov si, 8000h ;color   mov cx, 75*256+100 ;coordi...
Give a code snippet in #X86_Assembly Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon foll...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Swift
Swift
extension Int { init(romanNumerals: String) { let values = [ ( "M", 1000), ("CM", 900), ( "D", 500), ("CD", 400), ( "C", 100), ("XC", 90), ( "L", 50), ("XL", 40), ( "X", 10), (...
Give a code snippet in #Swift Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, st...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Slate
Slate
Platform current nodeName
Give a code snippet in #Slate Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#FunL
FunL
import lists.zipWithIndex import util.Regex   data Rule( birth, survival )   val Mirek = Regex( '([0-8]+)/([0-8]+)' ) val Golly = Regex( 'B([0-8]+)/S([0-8]+)' )   def decode( rule ) = def makerule( b, s ) = Rule( [int(d) | d <- b], [int(d) | d <- s] )   case rule Mirek( s, b ) -> makerule( b, s ) Golly( b, ...
Give a code snippet in #FunL The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#AutoHotkey
AutoHotkey
MsgBox, % "The mean time is: " MeanTime(["23:00:17", "23:40:20", "00:12:45", "00:17:19"])   MeanTime(t, x=0, y=0) { static c := ATan(1) / 45 for k, v in t { n := StrSplit(v, ":") r := c * (n[1] * 3600 + n[2] * 60 + n[3]) / 240 x += Cos(r) y += Sin(r) } r := atan2(x, y) / c r := (r < 0 ? r + 360 : r) / 15 ...
Give a code snippet in #AutoHotkey Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the i...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() { fmt.Println(ex([]int32{-7, 1, 5, 2, -4, 3, 0}))   // sequence of 1,000,000 random numbers, with values // chosen so that it will be likely to have a couple // of equalibrium indexes. rand.Seed(time.Now().UnixNano()) v...
Give a code snippet in #Go An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = ...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{low, high} = {1, 7}; SolveValues[{a + b == b + c + d == d + e + f == f + g, low <= a <= high, low <= b <= high, low <= c <= high, low <= d <= high, low <= e <= high, low <= f <= high, low <= g <= high, a != b != c != d != e != f != g}, {a, b, c, d, e, f, g}, Integers]   {low, high} = {3, 9}; SolveValues[{a + ...
Give a code snippet in #Mathematica.2FWolfram_Language 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the lett...
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...
#Factor
Factor
1000 [1,b] [ >float sq recip ] map-sum
Give a code snippet in #Factor 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 = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Wren
Wren
/* active_directory_connect.wren */   foreign class LDAP { construct init(host, port) {}   foreign simpleBindS(name, password)   foreign unbind() }   class C { foreign static getInput(maxSize) }   var name = "" while (name == "") { System.write("Enter name : ") name = C.getInput(40) }   var pass...
Give a code snippet in #Wren The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Python
Python
def bubble_sort(seq): """Inefficiently sort the mutable sequence (list) in place. seq MUST BE A MUTABLE SEQUENCE.   As with list.sort() and random.shuffle this does NOT return """ changed = True while changed: changed = False for i in range(len(seq) - 1): if se...
Give a code snippet in #Python 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/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...
#AutoHotkey
AutoHotkey
Dijkstra(data, start){ nodes := [], dist := [], Distance := [], dist := [], prev := [], Q := [], min := "x" for each, line in StrSplit(data, "`n" , "`r") field := StrSplit(line,"`t"), nodes[field.1] := 1, nodes[field.2] := 1 , Distance[field.1,field.2] := field.3, Distance[field.2,field.1] := field.3 dist[start]...
Give a code snippet in #AutoHotkey 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_n-step_number_sequences
Padovan n-step number sequences
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n ==...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   ------------------ PADOVAN N-STEP NUMBERS ----------------   -- padovans :: [Int] on padovans(n) script recurrence on |λ|(xs) {item 1 of xs, ¬ rest of xs & {sum(take(n, xs)) as integer}} en...
Give a code snippet in #AppleScript As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n,...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Kotlin
Kotlin
fun facti(n: Int) = when { n < 0 -> throw IllegalArgumentException("negative numbers not allowed") else -> { var ans = 1L for (i in 2..n) ans *= i ans } }   fun factr(n: Int): Long = when { n < 0 -> throw IllegalArgumentException("negative numbers not allowed") n < 2 -> 1L ...
Give a code snippet in #Kotlin Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Frink
Frink
  for line = lines["file:yourfile.txt"] println[line]  
Give a code snippet in #Frink Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/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 |...
#J
J
compare=: < , = , >   cti=: dyad define select =. ;@# English =. ' is less than ';' is equal to ';' is greater than ' x (":@[, (compare select English"_), ":@]) y )
Give a code snippet in #J 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/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#Groovy
Groovy
import static java.util.stream.IntStream.rangeClosed   class Superpermutation { final static int nMax = 12   static char[] superperm static int pos static int[] count = new int[nMax]   static int factSum(int n) { return rangeClosed(1, n) .map({ m -> rangeClosed(1, m).reduce(1, { ...
Give a code snippet in #Groovy A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to u...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Forth
Forth
\ this prints five lines containing elements from the two \ words 'proc1' and 'proc2'. gotos are used here to jump \ into and out of the two words at various points, as well \ as to create a loop. this functions with ficl, pfe, \ gforth, bigforth, swiftforth, iforth, and vfxforth; it \ may work with other forths as wel...
Give a code snippet in #Forth Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom t...
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#ChucK
ChucK
// chuck this with other shreds to record to file // example> chuck foo.ck bar.ck rec   // arguments: rec:<filename>   // get name me.arg(0) => string filename; if( filename.length() == 0 ) "foo.wav" => filename;   // pull samples from the dac dac => Gain g => WvOut w => blackhole; // this is the output file name file...
Give a code snippet in #ChucK Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate....
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a[2] = "string"; a["sometext"] = 23;
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubl...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#Julia
Julia
function gnomesort!(arr::Vector) i, j = 1, 2 while i < length(arr) if arr[i] ≤ arr[i+1] i = j j += 1 else arr[i], arr[i+1] = arr[i+1], arr[i] i -= 1 if i == 0 i = j j += 1 end end ...
Give a code snippet in #Julia 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/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Perl
Perl
use strict; use warnings; use 5.010; if (-t) { say "Input comes from tty."; } else { say "Input doesn't come from tty."; }
Give a code snippet in #Perl Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Picat
Picat
go => N = random(1,10), do print("Guess a number: ") while (read_int() != N), println("Well guessed!").
Give a code snippet in #Picat Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Frink
Frink
stripchars[str, remove] := { set = toSet[chars[remove]] return char[remove[char[str], {|c, set| set.contains[c]}, set]] }   println[stripchars["She was a soul stripper. She took my heart!","aei"]]  
Give a code snippet in #Frink Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in t...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#OCaml
OCaml
let obj1 = object method name = "T" end   let obj2 = object method name = "S" end   let () = print_endline (Oo.copy obj1)#name; (* prints "T" *) print_endline (Oo.copy obj2)#name; (* prints "S" *)
Give a code snippet in #OCaml An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#VBA
VBA
Type Tuple Priority As Integer Data As String End Type Dim a() As Tuple Dim n As Integer 'number of elements in array, last element is n-1 Private Function Left(i As Integer) As Integer Left = 2 * i + 1 End Function Private Function Right(i As Integer) As Integer Right = 2 * i + 2 End Function Private F...
Give a code snippet in #VBA A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priori...
christopher/rosetta-code
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Elixir
Elixir
#! /usr/bin/env elixir defmodule Mentions do def get(url) do {:ok, {{_, 200, _}, _, body}} = url |> String.to_charlist() |> :httpc.request() data = List.to_string(body) if Regex.match?(~r|<!Doctype HTML.*<Title>URL Not Found</Title>|s, data) do {:error, "log file not found"} el...
Give a code snippet in #Elixir Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you o...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#ALGOL_W
ALGOL W
% declare some variables % integer a1, a2; real b; long real c; complex d; long complex f; logical g; bits h; string(32) j;   % assign "initial values" % f := d := c := b := a2 := a1 := 0; % multiple assignment % g := false; h := #a0; j := "Hello, World!";  
Give a code snippet in #ALGOL_W Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Maple
Maple
FlippingBits := module() export ModuleApply; local gameSetup, flip, printGrid, checkInput; local board;   gameSetup := proc(n) local r, c, i, toFlip, target; randomize(): target := Array( 1..n, 1..n, rand(0..1) ); board := copy(target); for i to rand(3..9)() do toFlip := [0, 0]; toFlip[1] := StringT...
Give a code snippet in #Maple The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one mov...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#PicoLisp
PicoLisp
(load "@lib/simul.l") (seed (in "/dev/urandom" (rd 8))) (de pieceN (P) (case P ("p" 8) ("q" 1) (T 2) ) ) (de pieceset () (let C 0 (make (for P (conc (cons "p") (shuffle '("r" "n" "b" "q"))) (let (X (pieceN P) N (rand 0 (+ X C))) (do N ...
Give a code snippet in #PicoLisp Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacen...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#XLISP
XLISP
[1] (define my-empty-string "") ;; assign an empty string to a variable   MY-EMPTY-STRING [2] (string-null? my-empty-string)   #T [3] (string-null? "A non-empty string")   ()
Give a code snippet in #XLISP Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Oth...
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckBoolean { A=True Print Type$(A)="Double" B=1=1 Print Type$(B)="Boolean" Print A=B ' true Print A, B ' -1 True Def boolean C=True, D=False Print C, D , 1>-3 ' True False True K$=Str$(C) Print K$="True" ' True Function ShowBoolean$(&x) ...
Give a code snippet in #M2000_Interpreter 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/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Factor
Factor
USING: kernel math math.vectors sequences ; IN: rosetacode   : 1-order ( seq -- seq' ) [ rest-slice ] keep v- ;   : n-order ( seq n -- seq' ) dup 0 <= [ drop ] [ [ 1-order ] times ] if ;  
Give a code snippet in #Factor Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#Prolog
Prolog
  divisor(N, Div) :- Max is floor(sqrt(N)), between(1, Max, D), divmod(N, D, _, 0), (Div = D; Div is N div D, Div =\= D).   divisors(N, Divs) :- setof(M, divisor(N, M), Divs).   recip(A, B) :- B is 1 rdiv A.   sumrecip(N, A) :- divisors(N, [1 | Ds]), maplist(recip, Ds, As), sum_list(As, ...
Give a code snippet in #Prolog Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Maple
Maple
path := "file.txt": while (true) do input := readline(path): if input = 0 then break; end if: #The line is stored in input end do:
Give a code snippet in #Maple Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Sparkling
Sparkling
var odd = 13; if odd % 2 != 0 { print("odd"); }
Give a code snippet in #Sparkling Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Com...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PureBasic
PureBasic
typedef unsigned long long u8; typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;   #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) u8 ranval( ranctx *x ) { u8 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; }...
Give a code snippet in #PureBasic The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algo...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical 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 |...
#E
E
def logicalOperations(a :boolean, b :boolean) { return ["and" => a & b, "or" => a | b, "not" => !a, "xor" => a ^ b] }
Give a code snippet in #E 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/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Jsish
Jsish
/* Runtime evaluation in an environment, in Jsish */ function evalWithX(expr, a, b) { var x = a; var atA = eval(expr); x = b; var atB = eval(expr); return atB - atA; }   ;evalWithX('Math.exp(x)', 0, 1); ;evalWithX('Math.exp(x)', 1, 0);   /* =!EXPECTSTART!= evalWithX('Math.exp(x)', 0, 1) ==> 1.718281...
Give a code snippet in #Jsish x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Stata
Stata
gen leap = mod(year,400)==0 | mod(year,4)==0 & mod(year,100)!=0
Give a code snippet in #Stata Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#Elixir
Elixir
defmodule Permutation do def by_swap(n) do p = Enum.to_list(0..-n) |> List.to_tuple by_swap(n, p, 1) end   defp by_swap(n, p, s) do IO.puts "Perm: #{inspect for i <- 1..n, do: abs(elem(p,i))} Sign: #{s}" k = 0 |> step_up(n, p) |> step_down(n, p) if k > 0 do pk = elem(p,k) i = if p...
Give a code snippet in #Elixir Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. ...
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 ...
#Slate
Slate
#(7 5 2 9 0 -1) sort
Give a code snippet in #Slate 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/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#VBScript
VBScript
class accumulator dim A public default function acc(x) A = A + x acc = A end function public property get accum accum = A end property end class
Give a code snippet in #VBScript A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Run_BASIC
Run BASIC
print multInv(42, 2017) end   function multInv(a,b) b0 = b multInv = 1 if b = 1 then goto [endFun] while a > 1 q = a / b t = b b = a mod b a = t t = x0 x0 = multInv - q * x0 multInv = int(t) wend if multInv < 0 then multInv = multInv + b0 [endFun] end function
Give a code snippet in #Run_BASIC From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Standard_ML
Standard ML
  exception Found of string ;   val divisors = fn n => let val rec divr = fn ( c, divlist ,i) => if c <2*i then c::divlist else divr (if c mod i = 0 then (c,i::divlist,i+1) else (c,divlist,i+1) ) in divr (n,[],1) end;     val subsetSums = fn M => fn input => let val getnrs = fn (v,x) => ...
Give a code snippet in #Standard_ML Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Racket
Racket
#lang racket/base   (define (copy-prefab-struct str) (apply make-prefab-struct (vector->list (struct->vector str))))   (struct point (x y) #:prefab) (struct point/color point (color) #:prefab)     (let* ([original (point 0 0)] [copied (copy-prefab-struct original)]) (displayln copied) (displayln (eq? origi...
Give a code snippet in #Racket An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x wer...
christopher/rosetta-code
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cyli...
#Go
Go
package main   import ( "fmt" "math/rand" "strings" "time" )   var cylinder = [6]bool{}   func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t }   func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } ...
Give a code snippet in #Go The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. I...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Lah] Lah[n_?Positive, 0] := 0 Lah[0, k_?Positive] := 0 Lah[n_, n_] := 1 Lah[n_, 1] := n! Lah[n_, k_] := (-1)^n (n! ((n - 1)!))/((k! ((k - 1)!)) ((n - k)!)) Table[Lah[i, j], {i, 0, 12}, {j, 0, 12}] // Grid Max[Lah[100, Range[0, 100]]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Wren
Wren
import "os" for Process import "io" for File   var args = Process.allArguments var s = File.read(args[1]).trim() var m = {} for (c in s) { var d = m[c] m[c] = (d) ? d + 1 : 1 } var hm = 0 for (k in m.keys) { var c = m[k] hm = hm + c * c.log2 } var l = s.count System.print(l.log2 - hm/l)
Give a code snippet in #Wren Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Delphi
Delphi
USING: formatting io kernel sequences ; IN: rosetta-code.fasta   : process-fasta-line ( str -- ) dup ">" head? [ rest "\n%s: " printf ] [ write ] if ;   : main ( -- ) readln rest "%s: " printf [ process-fasta-line ] each-line ;   MAIN: main
Give a code snippet in #Delphi In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rose...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Ada
Ada
with Ada.Finalization;   package BT is   type Balanced_Ternary is private;   -- conversions function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function...
Give a code snippet in #Ada Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thu...
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 |...
#Python
Python
"abcd".startswith("ab") #returns True "abcd".endswith("zn") #returns False "bb" in "abab" #returns False "ab" in "abab" #returns True loc = "abab".find("bb") #returns -1 loc = "abab".find("ab") #returns 0 loc = "abab".find("ab",loc+1) #returns 2
Give a code snippet in #Python Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, base...
#PowerShell
PowerShell
  function db { [CmdletBinding(DefaultParameterSetName="None")] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$false, Position=0, ParameterSetName="Add a new entry")] [string] $Path = ".\SimpleDatabase.csv",   [Parameter...
Give a code snippet in #PowerShell Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It cou...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#Kotlin
Kotlin
// version 1.1.2   import java.math.BigDecimal import java.math.MathContext   val mc = MathContext(256)   fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)   class Frac : Comparable<Frac> { val num: Long val denom: Long   companion object { val ZERO = Frac(0, 1) val ONE = ...
Give a code snippet in #Kotlin Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1...
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: * * * * * * * * * * * * * * * ...
#Kotlin
Kotlin
// version 1.1.2   const val ORDER = 4 const val SIZE = 1 shl ORDER   fun main(args: Array<String>) { for (y in SIZE - 1 downTo 0) { for (i in 0 until y) print(" ") for (x in 0 until SIZE - y) print(if ((x and y) != 0) " " else "* ") println() } }
Give a code snippet in #Kotlin 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/Topological_sort
Topological 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 ...
#Bracmat
Bracmat
( ("des_system_lib".std synopsys "std_cell_lib" "des_system_lib" dw02 dw01 ramlib ieee) (dw01.ieee dw01 dware gtech) (dw02.ieee dw02 dware) (dw03.std synopsys dware dw03 dw02 dw01 ieee gtech) (dw04.dw04 ieee dw01 dware gtech) (dw05.dw05 ieee dware) (dw06.dw06 ieee dware) (d...
Give a code snippet in #Bracmat 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/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 ...
#True_BASIC
True BASIC
FUNCTION fibonacci (n) LET n1 = 0 LET n2 = 1 FOR k = 1 TO ABS(n) LET sum = n1 + n2 LET n1 = n2 LET n2 = sum NEXT k IF n < 0 THEN LET fibonacci = n1 * ((-1) ^ ((-n) + 1)) ELSE LET fibonacci = n1 END IF END FUNCTION   PRINT fibonacci(0)  ! 0 PRINT fibo...
Give a code snippet in #True_BASIC 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/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Picat
Picat
go => pi2(1,0,1,1,3,3,0), nl.   pi2(Q,R,T,K,N,L,C) => if C == 50 then nl, pi2(Q,R,T,K,N,L,0) else if (4*Q + R-T) < (N*T) then print(N), P := 10*(R-N*T), pi2(Q*10, P, T, K, ((10*(3*Q+R)) div T)-10*N, L,C+1) else P := (2*Q+R)*L, M := (Q*(7*K)+2+(R*L)) di...
Give a code snippet in #Picat Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#C.23
C#
using System;   struct Fraction : IEquatable<Fraction>, IComparable<Fraction> { public readonly long Num; public readonly long Denom;   public Fraction(long num, long denom) { if (num == 0) { denom = 1; } else if (denom == 0) { throw new Ar...
Give a code snippet in #C.23 Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (a...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Ruby
Ruby
# query.rb require 'fiddle'   # Look for a C variable named QueryPointer. # Raise an error if it is missing. c_var = Fiddle.dlopen(nil)['QueryPointer']   int = Fiddle::TYPE_INT voidp = Fiddle::TYPE_VOIDP sz_voidp = Fiddle::SIZEOF_VOIDP   # Implement the C function # int Query(void *data, size_t *length) # in Ruby cod...
Give a code snippet in #Ruby This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Ruby
Ruby
class Integer def factors() (1..self).select { |n| (self % n).zero? } end end p 45.factors
Give a code snippet in #Ruby Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#AutoHotkey
AutoHotkey
x = 1 If x MsgBox, x is %x% Else If x > 1 MsgBox, x is %x% Else MsgBox, x is %x%
Give a code snippet in #AutoHotkey Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Co...
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...
#SQL
SQL
CREATE TABLE t1 (n REAL); -- this is postgresql specific, fill the table INSERT INTO t1 (SELECT generate_series(1,1000)::REAL); WITH tt AS ( SELECT 1/(n*n) AS recip FROM t1 ) SELECT SUM(recip) FROM tt;  
Give a code snippet in #SQL Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Perl
Perl
print substr("knight",1), "\n"; # strip first character print substr("socks", 0, -1), "\n"; # strip last character print substr("brooms", 1, -1), "\n"; # strip both first and last characters
Give a code snippet in #Perl The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If...
christopher/rosetta-code