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/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#CoffeeScript
CoffeeScript
  combos = (arr, k) -> return [ [] ] if k == 0 return [] if arr.length == 0   combos_with_head = ([arr[0]].concat combo for combo in combos arr, k-1) combos_sans_head = combos arr[1...], k combos_with_head.concat combos_sans_head   arr = ['iced', 'jam', 'plain'] console.log "valid pairs from #{arr.join ','}:"...
Give a code snippet in #CoffeeScript The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each mem...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Arturo
Arturo
print crc "The quick brown fox jumps over the lazy dog"
Give a code snippet in #Arturo Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets th...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def romanEnc /# n -- s #/ var number "" var res ( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" ) ( 50 "L" ) ( 40 "XL" ) ( 10 "X" ) ( 9 "IX" ) ( 5 "V" ) ( 4 "IV" ) ( 1 "I" ) )   len for get 1 get number over / int numbe...
Give a code snippet in #Phixmonti Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a...
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.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT   datei="rosetta.txt" ERROR/STOP OPEN (datei,READ,-std-)   ACCESS q: READ/RECORDS/UTF8 $datei s,line LOOP READ/NEXT/EXIT q PRINT line ENDLOOP ENDACCESS q  
Give a code snippet in #TUSCRIPT 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/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Objeck
Objeck
  bundle Default { class VigenereCipher { function : Main(args : String[]) ~ Nil { key := "VIGENERECIPHER"; ori := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; enc := encrypt(ori, key); IO.Console->Print("encrypt: ")->PrintLine(enc); I...
Give a code snippet in #Objeck Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of i...
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...
#ARM_Assembly
ARM Assembly
.string "PRG"   lcd_ptr .req r4 active_fb .req r5 inactive_fb .req r6 offset_r .req r7 backup_fb .req r8   @ start push {r4-r10, r12, lr}   ldr lcd_ptr, =0xC0000000 @ address of the LCD controller adr offset_r, offsets ldrh r0, [offset_r, #6] @ 0xffff is already in memory because -1 is in the offsets table ...
Give a code snippet in #ARM_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { class Quaternion { \\ by default are double a,b,c,d Property ToString$ { Value { link parent a,b,c, d to a,b,c,d value$=format$("{0} + {1}i + {2}j + {3}k",a,b,c,d) } ...
Give a code snippet in #M2000_Interpreter Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a com...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#jq
jq
# Test case 1: . 1 1   # Test case 2: 1+1 null 2   # Test case 3 (with the wrong result): 1+1 null 0   # A test case with a function definition: def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial 3 6
Give a code snippet in #jq Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { print (a(1) && b(1)) print (a(1) || b(1)) print (a(0) && b(1)) print (a(0) || b(1)) }     function a(x) { print " x:"x return x } function b(y) { print " y:"y return y }
Give a code snippet in #AWK Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resou...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Nanoquery
Nanoquery
class MyClass declare name   // constructors are methods with the same name as the class def MyClass(name) this.name = name end   def getName() return name end end   // instantiate a new MyClass object inst = new(MyClass, "name string goes here")   // display the name value println inst.getName()
Give a code snippet in #Nanoquery In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#OCaml
OCaml
let () = let s = "The quick brown fox jumps over the lazy dog" in let crc = Zlib.update_crc 0l s 0 (String.length s) in Printf.printf "crc: %lX\n" crc
Give a code snippet in #OCaml Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Delphi
Delphi
  program Fork_app;   {$APPTYPE CONSOLE}   uses System.Threading;   procedure Fork; begin Writeln('Spawned Thread'); end;   var t: ITask;   begin t := TTask.Run(fork);   Writeln('Main Thread');   TTask.WaitForAll(t); Readln; end.
Give a code snippet in #Delphi Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#D
D
import std.stdio: writeln;   void main() { // the associative array auto aa = ["alice":2, "bob":97, "charlie":45];   // how to iterate key/value pairs: foreach (key, value; aa) writeln("1) Got key ", key, " with value ", value); writeln();   // how to iterate the keys: foreach (key, ...
Give a code snippet in #D Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compoun...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Python
Python
class Vector: def __init__(self,m,value): self.m = m self.value = value self.angle = math.degrees(math.atan(self.m)) self.x = self.value * math.sin(math.radians(self.angle)) self.y = self.value * math.cos(math.radians(self.angle))   def __add__(self,vector): """ ...
Give a code snippet in #Python Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Yabasic
Yabasic
sub decode_url$(s$) local res$, ch$   while(s$ <> "") ch$ = left$(s$, 1) if ch$ = "%" then ch$ = chr$(dec(mid$(s$, 2, 2))) s$ = right$(s$, len(s$) - 3) else if ch$ = "+" ch$ = " " s$ = right$(s$, len(s$) - 1) endif res$ = res$ + ch...
Give a code snippet in #Yabasic This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencode...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#AWK
AWK
  # syntax: GAWK -f PIG_THE_DICE_GAME.AWK # converted from LUA BEGIN { players = 2 p = 1 # start with first player srand() printf("Enter: Hold or Roll?\n\n") while (1) { printf("Player %d, your score is %d, with %d temporary points\n",p,scores[p],points) getline reply reply = toupp...
Give a code snippet in #AWK The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to the...
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...
#MATLAB
MATLAB
function [gcdValue] = greatestcommondivisor(integer1, integer2) gcdValue = gcd(integer1, integer2);
Give a code snippet in #MATLAB 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   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#Ol
Ol
  (define (lexorder a b) (cond ((null? b) #false) ((null? a) #true) ((< (car a) (car b)) #true) ((> (car a) (car b)) #false) (else (lexorder (cdr a) (cdr b)))))   (print (lexorder '(1 2 3) '(1 2 3 4))) ; => true (print (lexorder '(1 2 4) '(1 2 3))) ; => false (print (lexorder...
Give a code snippet in #Ol sorting 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 | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Forth
Forth
CREATE s ," Hello world" \ create string "s" s C@ ( -- length=11 ) s COUNT ( addr len ) \ convert to a stack string, described below
Give a code snippet in #Forth Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme cont...
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: * * * * * * * * * * * * * * * ...
#C.23
C#
using System; using System.Collections;   namespace RosettaCode { class SierpinskiTriangle { int len; BitArray b;   public SierpinskiTriangle(int n) { if (n < 1) { throw new ArgumentOutOfRangeException("Order must be greater than zero"); } ...
Give a code snippet in #C.23 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/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h>   bool is_sorted(int *a, int n) { while ( --n >= 1 ) { if ( a[n] < a[n-1] ) return false; } return true; }   void shuffle(int *a, int n) { int i, t, r; for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } } ...
Give a code snippet in #C 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Tcl
Tcl
# More sophisticated versions are possible, such as playing a bell sample # using the Snack library. proc ringTheBell {} { puts -nonewline "\a" }   # The code to convert the (parsed) time into rings of the ship's bell and # printing of the name of the bell. proc strikeBell {hour minute} { global suppressNormalO...
Give a code snippet in #Tcl Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave o...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#X86-64_Assembly
X86-64 Assembly
  option casemap:none option literals:on   ifndef __SOCKET_CLASS__ __SOCKET_CLASS__ equ 1 if @Platform eq windows64   WSADATA struct wVersion dw ? wHighVersion dw ? iMaxSockets dw ? iMaxUdpDg dw ? szDescription db 256 dup (?) szSystemStatus db 128 dup (?) lpVendorI...
Give a code snippet in #X86-64_Assembly Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { print isbb("[]") print isbb("][") print isbb("][][") print isbb("[][]") print isbb("[][][]") print isbb("[]][[]") }   function isbb(x) { s = 0 for (k=1; k<=length(x); k++) { c = substr(x,k,1) if (c=="[") {s++} else { if (c=="]") s-- }   if (s<0) {return 0} ...
Give a code snippet in #AWK Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nes...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#Common_Lisp
Common Lisp
(defun check-distribution (function n &optional (delta 1.0)) (let ((bins (make-hash-table))) (loop repeat n do (incf (gethash (funcall function) bins 0))) (loop with target = (/ n (hash-table-count bins)) for key being each hash-key of bins using (hash-value value) when (> (abs (- value ta...
Give a code snippet in #Common_Lisp This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing r...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ada
Ada
  with Ada.Text_Io; use Ada.Text_Io; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Gnat.Heap_Sort_G;   procedure Custom_Compare is   type StringArrayType is array (Natural range <>) of Unbounded_String;   Strings : StringArrayType := (Null_Unbounded_String, To_Unboun...
Give a code snippet in #Ada Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Scheme
Scheme
  #!r6rs   ;; PS-TK example: display frame + label   (import (rnrs) (lib pstk main) ; change this to refer to your PS/Tk installation )   (define tk (tk-start)) (tk/wm 'title tk "PS-Tk Example: Label")   (let ((label (tk 'create-widget 'label 'text: "Goodbye, world"))) (tk/place label 'height: 20 'wi...
Give a code snippet in #Scheme 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/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings, RankNTypes #-} import Reflex import Reflex.Dom import Data.Text (Text, pack, unpack) import Data.Map (Map, fromList, empty) import Text.Read (readMaybe)   width = 600 height = 500   type Point = (Float,Float) type Segment = (Point,Point)   data Ellipse = Ellipse {a :: Float, b :: Float,...
Give a code snippet in #Haskell A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#BBC_BASIC
BBC BASIC
10 FOR i% = 1 TO 15 20 PRINT FNcatalan(i%) 30 NEXT 40 END 50 DEF FNcatalan(n%) 60 IF n% = 0 THEN = 1 70 = 2 * (2 * n% - 1) * FNcatalan(n% - 1) / (n% + 1)
Give a code snippet in #BBC_BASIC Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Jsish
Jsish
#!/usr/local/bin/jsish puts(Info.argv0()); puts(console.args);
Give a code snippet in #Jsish Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#PARI.2FGP
PARI/GP
  \\ FRACTRAN \\ 4/27/16 aev fractran(val,ft,lim)={ my(ftn=#ft,fti,di,L=List(),j=0); while(val&&j<lim, listput(L,val); for(i=1,ftn, fti=ft[i]; di=denominator(fti); if(val%di==0, break));\\fend i val= numerator(fti)*val/di; j++);\\wend j return(Vec(L)); }   {\\ Executing: my(v=[17/91,78/85,19/51,23/38,29/33,7...
Give a code snippet in #PARI.2FGP FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an in...
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...
#Fortran
Fortran
    module SutherlandHodgmanUtil ! functions and type needed for Sutherland-Hodgman algorithm   ! -------------------------------------------------------- ! type polygon !type for polygons ! when you define a polygon, the first and the last vertices have to be the same integer :: n double precisio...
Give a code snippet in #Fortran 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 di...
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...
#J
J
def=: abc
Give a code snippet in #J 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 unk...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Dyalect
Dyalect
func f(n) { n == 0 ? 1 : n - m(f(n-1)) } and m(n) { n == 0 ? 0 : n - f(m(n-1)) }   print( (0..20).Map(i => f(i)).ToArray() ) print( (0..20).Map(i => m(i)).ToArray() )
Give a code snippet in #Dyalect Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <math.h>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 300, MY_TIMER...
Give a code snippet in #C.2B.2B Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change eve...
christopher/rosetta-code
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#PowerShell
PowerShell
#lang racket render-game-state send-message-to-client traverse-forest
Give a code snippet in #PowerShell Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding pref...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Groovy
Groovy
println ''' Time's a strange fellow; more he gives than takes (and he takes all) nor any marvel finds quite disappearance but some keener makes losing, gaining --love! if a world ends '''
Give a code snippet in #Groovy A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) follow...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Scala
Scala
def fromRoman( r:String ) : Int = { val arabicNumerals = List("CM"->900,"M"->1000,"CD"->400,"D"->500,"XC"->90,"C"->100, "XL"->40,"L"->50,"IX"->9,"X"->10,"IV"->4,"V"->5,"I"->1)   var s = r arabicNumerals.foldLeft(0){ (n,t) => { val l = s.length; s = s.rep...
Give a code snippet in #Scala 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/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#Perl
Perl
q)3*2+1 9 q)(3*2)+1 / Brackets give the usual order of precedence 7 q)x:5 q)(x+5; x:20; x-5) 25 20 0
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Zig
Zig
  const std = @import("std"); pub fn main() !void { const stdout_wr = std.io.getStdOut().writer(); while (true) try stdout_wr.writeAll("SPAM\n"); }  
Give a code snippet in #Zig Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#Polyglot:PL.2FI_and_PL.2FM
Polyglot:PL/I and PL/M
/* FIND THE SMALLEST NUMBER > THE PREVIOUS ONE WITH EXACTLY N DIVISORS */   sequence_100H: procedure options (main);   /* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */ /* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES ...
Give a code snippet in #Polyglot:PL.2FI_and_PL.2FM Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: sma...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Python
Python
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Give a code snippet in #Python Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itsel...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Logo
Logo
to join :delimiter :list [:result []] output cond [ [ [empty? :list]  :result ] [ [empty? :result] (join :delimiter butfirst :list first :list) ] [ else (join :delimiter butfirst :list (word :result :delimiter first :list)) ] ] end   to quibble :list...
Give a code snippet in #Logo Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An inp...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#11l
11l
F yinyang(n = 3) V radii = [1, 3, 6].map(i -> i * @n) V ranges = radii.map(r -> Array(-r .. r)) V squares = ranges.map(rnge -> multiloop(rnge, rnge, (x, y) -> (x, y))) V circles = zip(squares, radii).map((sqrpoints, radius) -> sqrpoints.filter((x, y) -> x*x + y*y <= @radius^2)) V m = Dict(squares.last, (...
Give a code snippet in #11l One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp...
#Action.21
Action!
BYTE FUNC AtasciiToInternal(CHAR c) BYTE c2   c2=c&$7F IF c2<32 THEN RETURN (c+64) ELSEIF c2<96 THEN RETURN (c-32) FI RETURN (c)   PROC CharOut(CARD x BYTE y CHAR c) BYTE i,j,v CARD addr   addr=$E000+AtasciiToInternal(c)*8 FOR j=0 TO 7 DO v=Peek(addr) i=8 WHILE i>0 DO IF (v&1)=0 THEN...
Give a code snippet in #Action.21 Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#ML.2FI
ML/I
MCSKIP "WITH" NL "" CSV to HTML "" assumes macros on input stream 1, terminal on stream 2 MCSKIP MT,[] MCSKIP SL WITH ~ MCINS %. "" C1=th before header output, td afterwards MCCVAR 1,2 MCSET C1=[th] "" HTML escapes MCDEF < AS [[&lt;]] MCDEF > AS [[&gt;]] MCDEF & AS [[&amp;]] "" Main line processing MCDEF SL N1 OPT , N1...
Give a code snippet in #ML.2FI Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task C...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Ruby
Ruby
require 'date'   (2008..2121).each {|year| puts "25 Dec #{year}" if Date.new(year, 12, 25).sunday? }
Give a code snippet in #Ruby A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#J
J
colnumeric=: 0&".&.>@{`[`]}   data=: 1 colnumeric |: fixcsv 0 :0 Lagos, 21 Cairo, 15.2 Kinshasa-Brazzaville, 11.3 Greater Johannesburg, 7.55 Mogadishu, 5.85 Khartoum-Omdurman, 4.98 Dar Es Salaam, 4.7 Alexandria, 4.58 Abidjan, 4.4 Casablanca, 3.98 )
Give a code snippet in #J Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit]...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Oforth
Oforth
"999" 1 + println "999" asInteger 1 + asString println
Give a code snippet in #Oforth Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Oforth
Oforth
: powmod(base, exponent, modulus) 1 exponent dup ifZero: [ return ] while ( dup 0 > ) [ dup isEven ifFalse: [ swap base * modulus mod swap ] 2 / base sq modulus mod ->base ] drop ;
Give a code snippet in #Oforth Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373...
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Swift
Swift
let negInf = -1.0 / 0.0 let inf = 1.0 / 0.0 //also Double.infinity let nan = 0.0 / 0.0 //also Double.NaN let negZero = -2.0 / inf   println("Negative inf: \(negInf)") println("Positive inf: \(inf)") println("NaN: \(nan)") println("Negative 0: \(negZero)") println("inf + -inf: \(inf + negInf)") println("0 * NaN: \(0 * n...
Give a code snippet in #Swift The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language ...
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...
#Raku
Raku
use SVG;   role Lindenmayer { has %.rules; method succ { self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) } }   my $dragon = "FX" but Lindenmayer( { X => 'X+YF+', Y => '-FX-Y' } );   $dragon++ xx ^15;   my @points = 215, 350;   for $dragon.comb { state ($x, $y) = @points[0,1];...
Give a code snippet in #Raku 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#J
J
bead=: [: +/ #"0&1
Give a code snippet in #J 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...
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
#Aime
Aime
o_text("Hello world!\n");
Give a code snippet in #Aime 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/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#PowerShell
PowerShell
  function Out-Quibble { [OutputType([string])] Param ( # Zero or more strings. [Parameter(Mandatory=$false, Position=0)] [AllowEmptyString()] [string[]] $Text = "" )   # If not null or empty... if ($Text) { # Remove empty strings from the arra...
Give a code snippet in #PowerShell Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". ...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Fortran
Fortran
INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT)
Give a code snippet in #Fortran Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the s...
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
#Scilab
Scilab
tiles=[1:15,0]; solution=[tiles(1:4);... tiles(5:8);... tiles(9:12);... tiles(13:16)]; solution=string(solution); solution(16)=" ";   init_pos=grand(1,"prm",tiles); puzzle=[init_pos(1:4);... init_pos(5:8);... init_pos(9:12);... init_pos(13:16)]; puzzle=string(puzzle...
Give a code snippet in #Scilab 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/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. count-in-octal.   ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION dec-to-oct . DATA DIVISION. WORKING-STORAGE SECTION. 01 i PIC 9(18).   PROCEDURE DIVISION. PERFORM VARYING i FROM 1 BY 1 UNTIL i = ...
Give a code snippet in #COBOL Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Elixir
Elixir
defmodule RC do def narcissistic(m) do Enum.reduce(1..10, [0], fn digits,acc -> digitPowers = List.to_tuple(for i <- 0..9, do: power(i, digits)) Enum.reduce(power(10, digits-1) .. power(10, digits)-1, acc, fn n,result -> sum = divsum(n, digitPowers, 0) if n == sum do if lengt...
Give a code snippet in #Elixir A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#ML
ML
fun hail (x = 1) = [1] | (x rem 2 = 0) = x :: hail (x div 2) | x = x :: hail (x * 3 + 1)   fun hailstorm ([], i, largest, largest_at) = (largest_at, largest) | (x :: xs, i, largest, largest_at) = let val k = len (hail x) in if k > largest then hailstorm (xs, i + 1, k, i) else ha...
Give a code snippet in #ML The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#jq
jq
99 | (. - range(0;.+1) ) | " \(.) bottles of beer on the wall \(.) bottles of beer Take one down, pass it around \(.) bottles of beer on the wall"
Give a code snippet in #jq Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bo...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#J
J
ccd =. 10 | 10 - 10 | [: +/ [: , 10 (#.^:_1) (8 $ 1 2) * '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#' i. ] ccd '68389X10' 5
Give a code snippet in #J This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric cod...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#AutoHotkey
AutoHotkey
Narcissist(Input) { FileRead, Source, % A_ScriptFullPath return Input == Source ? "accept" : "reject" }
Give a code snippet in #AutoHotkey Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, a...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Guess_the_Number Sub Main() Dim random As New Random() Dim secretNum As Integer = random.Next(10) + 1 Dim gameOver As Boolean = False Console.WriteLine("I am thinking of a number from 1 to 10. Can you guess it?") Do Dim guessNum As Integer Conso...
Give a code snippet in #Visual_Basic_.NET 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 wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Clojure
Clojure
  (def poem "---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert -----------------------")   (dorun (map println (map #(apply str (interpose "...
Give a code snippet in #Clojure Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by sp...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func Halve(N); \Return half of N int N; return N>>1;   func Double(N); \Return N doubled int N; return N<<1;   func IsEven(N); \Return 'true' if N is an even number int N; return (N&1)=0;   func EthiopianMul(A, B); \Multiply A times B ...
Give a code snippet in #XPL0 Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#dc
dc
1 2 SaSbLaLb f =2 1
Give a code snippet in #dc Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#Retro
Retro
-3 5 out wait 5 in !cw -4 5 out wait 5 in !ch
Give a code snippet in #Retro Determine the height and width of the terminal, and store this information into variables for subsequent use.
christopher/rosetta-code
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g...
#Pascal
Pascal
  program TruthTables; const StackSize = 80;   type TVariable = record Name: Char; Value: Boolean; end;   TStackOfBool = record Top: Integer; Elements: array [0 .. StackSize - 1] of Boolean; end;   var Expression: string; Variables: array [0 .. 23] of TVariable; VariablesLength: Integer;...
Give a code snippet in #Pascal A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#BBC_BASIC
BBC BASIC
INSTALL @lib$ + "CLASSLIB"   REM Create parent class with void 'doprint' method: DIM PrintableShape{doprint} PROC_class(PrintableShape{})   REM Create derived class for Point: DIM Point{x#, y#, setxy, retx, rety, @constructor, @@destructor} PROC_inherit(Point{}, PrintableShape{...
Give a code snippet in #BBC_BASIC Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Phix
Phix
function heroArea(integer a, b, c) atom s = (a+b+c)/2 return sqrt(max(s*(s-a)*(s-b)*(s-c),0)) end function function hero(atom h) return remainder(h,1)=0 and h>0 end function sequence list = {} integer tries = 0 for a=1 to 200 do for b=1 to a do for c=1 to b do tries += 1 ...
Give a code snippet in #Phix Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#VBA
VBA
Option Explicit Option Base 1   Function Quad(ByVal f As String, ByVal a As Double, _ ByVal b As Double, ByVal n As Long, _ ByVal u As Variant, ByVal v As Variant) As Double Dim m As Long, h As Double, x As Double, s As Double, i As Long, j As Long m = UBound(u) h = (b - a) / n s = 0# ...
Give a code snippet in #VBA Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Block[{start = SessionTime[], K, t0 = 0, t1, kt0, S = 0}, K[t_] = Sin[2 Pi f t] /. f -> 0.5; kt0 = K[t0]; While[True, t1 = SessionTime[] - start; S += (kt0 + (kt0 = K[t1])) (t1 - t0)/2; t0 = t1; If[t1 > 2, K[t_] = 0; If[t1 > 2.5, Break[]]]]; S]
Give a code snippet in #Mathematica.2FWolfram_Language In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside....
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Ring
Ring
  Class Animal Class Dog from Animal Class Cat from Animal Class Lab from Dog Class Collie from Dog  
Give a code snippet in #Ring This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types....
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Vala
Vala
int main() { string? s; while((s = stdin.read_line()) != null) { stdout.printf("%s\n", s); } return 0; }
Give a code snippet in #Vala Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Forth
Forth
: insert ( start end -- start ) dup @ >r ( r: v ) \ v = a[i] begin 2dup < \ j>0 while r@ over cell- @ < \ a[j-1] > v while cell- \ j-- dup @ over cell+ ! \ a[j] = a[j-1] repeat then r> swap ! ; \ a[j] = v   : sort ( array len -- ) 1 ?do dup i cells + insert loop drop ;   create test...
Give a code snippet in #Forth 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/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Mercury
Mercury
  :- module permutations2. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.     :- import_module list. :- import_module set_ordlist. :- import_module set. :- import_module solutions.   %% permutationSet(List, Set) is true if List is a permutation of Set: :- pred permutationSet(list(A)::out,se...
Give a code snippet in #Mercury Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   ge...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#XSLT
XSLT
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html" version="4.01" indent="yes"/>   <!-- Most XSLT processors have some way to supply a different value for this parameter --> <xsl:param name="column-count" select="3...
Give a code snippet in #XSLT Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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
define: #words -> #('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)'). words sortBy: [| :first :second | (first lexicographicallyCompare: second) isNegative]
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/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Haskell
Haskell
import qualified Data.Map as M   myMap :: M.Map String Int myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)]   main :: IO () main = (putStrLn . unlines) $ [ show . M.toList -- Pairs , show . M.keys -- Keys , show . M.elems -- Values ] <*> pure myMap
Give a code snippet in #Haskell Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections C...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#C.23
C#
  using System; using System.IO; using System.Linq; using System.Collections.Generic;     namespace Rosetta {   public enum TokenType { End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract, Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal, Op_equal, Op_noteq...
Give a code snippet in #C.23 Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Rendezvous
Rendezvous
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
#Racket
Racket
  #lang racket   ;;; Rendezvous primitives implemented in terms of synchronous channels. (define (send ch msg) (define handshake (make-channel)) (channel-put ch (list msg handshake)) (channel-get handshake) (void))   (define (receive ch action) (match-define (list msg handshake) (channel-get ch)) (action ms...
Give a code snippet in #Racket Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
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 ...
#LSE64
LSE64
over : 2 pick 2dup : over over even? : 1 & 0 =   # trial n d yields "n d 0/1 false" or "n d+2 true" trial : 2 + true trial : 2dup % 0 = then 0 false trial : 2dup dup * < then 1 false trial-loop : trial &repeat   # prime? n yields flag prime? : 3 trial-loop >flag drop drop prime? : dup even? ...
Give a code snippet in #LSE64 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 ...
#Pascal
Pascal
  { source file name on linux is ./p.p   -*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat Mar 11 23:55:25   a=./p && pc $a.p && $a Free Pascal Compiler version 3.0.0+dfsg-8 [2016/09/03] for x86_64 Copyright (c) 1993-2015 by Florian Klaempfl and others Target OS: Linu...
Give a code snippet in #Pascal 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/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum pos...
#F.23
F#
  // Minimum positive multiple in base 10 using only 0 and 1. Nigel Galloway: March 9th., 2020 let rec fN Σ n i g e l=if l=1||n=1 then Σ+1I else match (10*i)%l with g when n=g->Σ+10I**e |i->match Set.map(fun n->(n+i)%l) g with ...
Give a code snippet in #F.23 Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phras...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#F.23
F#
open System   let removeEmptyLists lists = lists |> List.filter (not << List.isEmpty) let flip f x y = f y x   let rec transpose = function | [] -> [] | lists -> (List.map List.head lists) :: transpose(removeEmptyLists (List.map List.tail lists))   // Using the backward composition operator "<<" (equivalent ...
Give a code snippet in #F.23 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Icon_and_Unicon
Icon and Unicon
procedure main() bitdemo(255,2) bitdemo(-15,3) end   procedure bitdemo(i,i2) write() demowrite("i",i) demowrite("i2",i2) demowrite("complement i",icom(i)) demowrite("i or i2",ior(i,i2)) demowrite("i and i2",iand(i,i2)) demowrite("i xor i2",ixor(i,i2)) demowrite("i shift " || i2,ishift(i,i2)...
Give a code snippet in #Icon_and_Unicon 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 O...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Arc
Arc
(= lshift '((0 1) (2 14) (1 2) (14 26))) (= rshift '((1 3) (4 15) (3 4) (15 26) (0 1)))   (= rot (fn (alpha shift) (let shift (mod shift 26) (string (cut alpha shift) (cut alpha 0 shift)))))   (= scramble-wheel (fn (alpha moves) (= oput '()) (up i 0 (- (len moves) 1) (push (cut alpha ((moves i) 0) ((mov...
Give a code snippet in #Arc Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there i...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Kotlin
Kotlin
// version 1.0.6   infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this   fun main(args: Array<String>) { val raining = true val needUmbrella = true iif (raining) println("Do I need an umbrella? ${if(needUmbrella) "Yes" else "No"}") }
Give a code snippet in #Kotlin Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the st...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
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 |...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings use warnings;   for ( 'shorter thelonger', 'abcd 123456789 abcdef 1234567' ) { print "\nfor strings => $_\n"; printf "length %d: %s\n", length(), $_ for sort { length $b <=> length $a } split; }
Give a code snippet in #Perl 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/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#COBOL
COBOL
PROGRAM-ID. Go-To-Example.   PROCEDURE DIVISION. Foo. DISPLAY "Just a reminder: GO TOs are evil."   GO TO Foo .
Give a code snippet in #COBOL Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct....
christopher/rosetta-code
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#Free_Pascal
Free Pascal
(* A mixture of the lyrics found in Wikipedia and the Ada version in Rosetta Code. It formats the lyrics like the Wikipedia one *) program OldLady;   uses SysUtils;   const MaxLadies = 9; //Number of iterations and array items Animals: array[1..MaxLadies + 1] of shortstring = ( //Add one for the song's end...
Give a code snippet in #Free_Pascal Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical ...
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,...
#Action.21
Action!
PROC Main() BYTE i    ;array storing 4 INT items with initialized values  ;negative values must be written as 16-bit unsigned numbers INT ARRAY a=[3 5 71 65535]    ;array storing 4 CARD items whithout initialization of values CARD ARRAY b(3)    ;array of BYTE items without allocation,  ;it may be used as an ...
Give a code snippet in #Action.21 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 r...
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
#E
E
<unsafe:java.lang.System>.getenv("HOME")
Give a code snippet in #E 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/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#Nim
Nim
import sequtils, strutils   type Square = seq[seq[int]]   func magicSquareOdd(n: Positive): Square = ## Build a magic square of odd order.   assert n >= 3 and (n and 1) != 0, "base must be odd and greater than 2." result = newSeqWith(n, newSeq[int](n))   var r = 0 c = n div 2 value = 0   while val...
Give a code snippet in #Nim A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a m...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#PHP
PHP
$i = 1024; while ($i > 0) { echo "$i\n"; $i >>= 1; }
Give a code snippet in #PHP Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward ...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#BCPL
BCPL
get "libhdr"   let lpd(n) = valof for i = n<=1 -> 1, n-1 to 1 by -1 if n rem i=0 resultis i   let start() be for i=1 to 100 $( writed(lpd(i), 3) if i rem 10=0 then wrch('*N') $)
Give a code snippet in #BCPL Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#8th
8th
  1 0 n:/ Inf? . cr  
Give a code snippet in #8th Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#R
R
dyn.load("my/special/R/lib.so") .Call("my_lib_fun", arg1, arg2)
Give a code snippet in #R Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#EDSAC_order_code
EDSAC order code
[ Loop with downward counter ==========================   A program for the EDSAC   Prints the integers 10 down to 0   The counter is stored at address 20@   Its initial value is 9 * 2^12 (9 in the high 5 bits, representing the character '9') and it counts down in steps of 2^12   Works with Initial Or...
Give a code snippet in #EDSAC_order_code Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   L...
christopher/rosetta-code