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 |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Haskell | Haskell |
-- Words are read from the standard input. We keep in memory only the current
-- set of longest, ordered words.
--
-- Limitation: the locale's collation order is not take into consideration.
isOrdered wws@(_:ws) = and $ zipWith (<=) wws ws
longestOrderedWords = reverse . snd . foldl f (0,[]) . filter isOrdered
... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Picat | Picat | go =>
Tests = ["In girum imus nocte et consumimur igni",
"this is a non palindrome string",
"anna ABcdcBA anna",
"anna ABcdcBA annax",
"A man, a plan, a canoe, pasta, heros, rajahs" ++
"a coloratura, maps, snipe, percale, macaroni, " ++
"a gag,... |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #C.2B.2B | C++ | #pragma once
#include <cmath>
#include <string>
#include <sstream>
#include <iomanip>
class Approx {
public:
Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}
operator std::string() const {
std::ostringstream os("");
os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Phix | Phix | with javascript_semantics
sequence summable = {true} -- (1 can be expressed as 1*1)
integer n = 2
while true do
integer sq = n*n
summable &= repeat(false,sq)
-- (process backwards to avoid adding sq more than once)
for i=length(summable)-sq to 1 by -1 do
if summable[i] then
summable[... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Raku | Raku | my @squares = ^∞ .map: *²; # Infinite series of squares
for 1..∞ -> $sq { # for every combination of all squares
my @sums = @squares[^$sq].combinations».sum.unique.sort;
my @run;
for @sums {
@run.push($_) and next unless @run.elems;
if $_ == @run.tail + 1 { @run.push: $_ } else { ... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #CoffeeScript | CoffeeScript | isWordChar = (c) -> /^\w/.test c
isLastChar = (c) -> c is '.'
# Pass a function that returns an input character and one that outputs a
# character. JS platforms' ideas of single-character I/O vary widely, but this
# abstraction is adaptable to most or all.
oddWord = (get, put) ->
forwardWord = ->
loop
# No magi... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Common_Lisp | Common Lisp | (defun odd-word (s)
(let ((stream (make-string-input-stream s)))
(loop for forwardp = t then (not forwardp)
while (if forwardp
(forward stream)
(funcall (backward stream)))) ))
(defun forward (stream)
(let ((ch (read-char stream)))
(write-char ch)
(if ... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #AutoHotkey | AutoHotkey | n := 22, n1 := n+1, v0 := v%n1% := 0 ; set grid dimensions, and fixed cells
Loop % n { ; draw a line of checkboxes
v%A_Index% := 0
Gui Add, CheckBox, % "y10 w17 h17 gCheck x" A_Index*17-5 " vv" A_Index
}
Gui Add, Button, x+5 y6, step ; button to step to next... |
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... | #Ada | Ada | generic
type Scalar is digits <>;
with function F (X : Scalar) return Scalar;
package Integrate is
function Left_Rectangular (A, B : Scalar; N : Positive) return Scalar;
function Right_Rectangular (A, B : Scalar; N : Positive) return Scalar;
function Midpoint_Rectangular (A, B : Scalar; N : Positi... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #Ada | Ada | with Ada.Text_Io;
with Ada.Integer_Text_Io;
procedure Equal_Rise_Fall is
use Ada.Text_Io;
function Has_Equal_Rise_Fall (Value : Natural) return Boolean is
Rises : Natural := 0;
Falls : Natural := 0;
Image : constant String := Natural'Image (Value);
Last : Character := Image (Image'Fir... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns TRUE if the number of digits in n followed by a higher digit (rises) #
# equals the number of digits followed by a lower digit (falls) #
# FALSE otherwise #
PROC rises equals falls = ( INT n )BOOL:
BE... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #Common_Lisp | Common Lisp | ;; Computes the initial guess for the root i of a n-order Legendre polynomial.
(defun guess (n i)
(cos (* pi
(/ (- i 0.25d0)
(+ n 0.5d0)))))
;; Computes and evaluates the n-order Legendre polynomial at the point x.
(defun legpoly (n x)
(let ((pa 1.0d0)
(pb x)
(pn))
(cond... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Factor | Factor | USING: accessors combinators.extras io io.encodings.binary
io.files io.files.info kernel prettyprint serialize ;
IN: rosetta-code.object-serialization
! Define two classes, item and armor. armor is a subclass of
! item.
TUPLE: item name value ;
TUPLE: armor < item physical-resistance fire-resistance ;
! Define bo... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Go | Go | package main
import (
"encoding/gob"
"fmt"
"os"
)
type printable interface {
print()
}
func main() {
// create instances
animals := []printable{
&Animal{Alive: true},
&Cat{},
&Lab{
Dog: Dog{Animal: Animal{Alive: true}},
Color: "yellow",
... |
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... | #BBC_BASIC | BBC BASIC | REM >oldlady
DIM swallowings$(6, 1)
swallowings$() = "fly", "+why", "spider", "That wriggled and wiggled and tickled inside her", "bird", ":How absurd", "cat", ":Fancy that", "dog", ":What a hog", "cow", "+how", "horse", "She's dead, of course"
FOR i% = 0 TO 6
PRINT "There was an old lady who swallowed a "; swallowin... |
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... | #BCPL | BCPL | get "libhdr"
let animal(n) =
n=0 -> "fly", n=1 -> "spider", n=2 -> "bird",
n=3 -> "cat", n=4 -> "dog", n=5 -> "goat",
n=6 -> "cow", n=7 -> "horse", valof finish
let line(n) =
n=0 -> "I don't know why she swallowed that fly,*NPerhaps she'll die.*N",
n=1 -> "That wiggled and ji... |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation... | #zkl | zkl | var [const] BI=Import.lib("zklBigNum"); // GMP
var kRE,kD, aRE,aD;
kRE,kD = ki();
aRE,aD = abrevCreate();
fcn naSuffixes(numStr){
var [const]
numRE=RegExp(0'^([+-]*\.*\d+[.]*\d*E*[+-]*\d*)^),
bangRE=RegExp(0'^(!+)^);
nstr:=(numStr - " ,").toUpper();
numRE.search(nstr);
nstr,r := nstr[numRE... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Haskell | Haskell | module Main where
import Text.Printf (printf)
import System.Environment (getArgs, getProgName)
tochka = ("tochka" , 0.000254)
liniya = ("liniya" , 0.00254)
centimeter = ("centimeter", 0.01)
diuym = ("diuym" , 0.0254)
vershok = ("vershok" , 0.04445)
piad = ("piad" , 0.1778)
fut... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #JavaScript | JavaScript | <html style="margin: 0;">
<head>
<title>Minimal WebGL Example</title>
<!-- This use of <script> elements is so that we can have multiline text
without quoting it inside of JavaScript; the web browser doesn't
actually do anything besides store the text of these. -->
<script id="shader-fs"... |
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... | #ERRE | ERRE |
PROGRAM ONE_OF_N
DIM CNT[10]
PROCEDURE ONE_OF_N(N->L)
LOCAL I
FOR I=1 TO N DO
IF RND(1)<=1.0/I THEN L=I END IF
END FOR
END PROCEDURE
BEGIN
N=10
RANDOMIZE(TIMER) ! init
FOR TEST=1 TO 1000000 DO
ONE_OF_N(N->L)
CNT[L]+=1
END FOR
FOR I=1 TO N DO
PRINT(CNT[I];)
END FOR
P... |
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... | #Euphoria | Euphoria | -- One of n lines in a file
include std/rand.e
include std/math.e
function one_of_n(integer n)
integer line_num = 1
for i = 2 to n do
if rnd() < 1 / i then
line_num = i
end if
end for
return line_num
end function
procedure main()
integer num_reps = 1000000, num_lines_in_file = 10
sequence lines = repe... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #Scala | Scala | def order[T](input: Seq[T], using: Seq[T], used: Seq[T] = Seq()): Seq[T] =
if (input.isEmpty || used.size >= using.size) input
else if (using diff used contains input.head)
using(used.size) +: order(input.tail, using, used :+ input.head)
else input.head +: order(input.tail, using, used) |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #Sidef | Sidef | func dsort(m, n) {
var h = Hash()
n.each {|item| h{item} := 0 ++ }
m.map {|item| h{item} := 0 -- > 0 ? n.shift : item}
}
<<'EOT'.lines.each { |line|
the cat sat on the mat | mat cat
the cat sat on the mat | cat mat
A B C A B C A B C | C A C A
A B C A B D A B E ... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Lua | Lua |
function showTable(tbl)
if type(tbl)=='table' then
local result = {}
for _, val in pairs(tbl) do
table.insert(result, showTable(val))
end
return '{' .. table.concat(result, ', ') .. '}'
else
return (tostring(tbl))
end
end
function sortTable(op)
local tbl = op.table or {}
local column = op.column o... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
write( if list_llt([1,2,1,3,2],[1,2,0,4,4,0,0,0]) then "true" else "false" )
end
procedure list_llt(L1,L2) #: returns L2 if L1 lexically lt L2 or fails
every i := 1 to min(*L1,*L2) do
if L1[i] << L2[i] then return L2
else if L1[i] >> L2[i] then fail
if *L1 < *L2 then return L2
end |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #zkl | zkl | fcn pascalTriangle(n){ // n<=0-->""
foreach i in (n){
c := 1;
print(" "*(2*(n-1-i)));
foreach k in (i+1){
print("%3d ".fmt(c));
c = c * (i-k)/(k+1);
}
println();
}
}
pascalTriangle(8); |
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... | #Scilab | Scilab | $ syntax expr: .(). + .() is -> 7; |
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... | #Seed7 | Seed7 | $ syntax expr: .(). + .() is -> 7; |
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... | #Sidef | Sidef | 1+2 * 3+4 # means: (1+2) * (3+4) |
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... | #Simula | Simula | 5 + b negated. "same as 5 + (b negated); unary > binary"
a abs - b sqrt "same as (a abs) - (b sqrt); unary > binary"
a bitAnd:1+a abs. "same as a bitAnd:(1+(a abs)); unary > binary > keyword"
(a bitAnd:1+a) bitOr:(b bitAnd:1+2 abs). "ditto"
"Beginners might be confused by:... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Huginn | Huginn | import Algorithms as algo;
import Mathematics as math;
import Network as net;
import Text as text;
main( argv_ ) {
url = size( argv_ ) > 1
? argv_[1]
: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt";
words = algo.materialize( algo.map( net.get( url ).stream, string.strip ), list );
ordered = algo... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Icon_and_Unicon | Icon and Unicon | link strings
procedure main(A)
f := open(\A[1]) | stop("Give dictionary file name on command line")
every (maxLen := 0, maxLen <= *(w := !f), w == csort(w)) do {
if maxLen <:= *w then maxList := [] #discard any shorter sorted words
put(maxList, w)
}
every write(!\maxList)
end |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #PicoLisp | PicoLisp | (de palindrome? (S)
(= (setq S (chop S)) (reverse S)) ) |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #Common_Lisp | Common Lisp | (defstruct uncertain-number
(value 0 :type number)
(uncertainty 0 :type number))
(defmethod print-object ((n uncertain-number) stream)
(format stream "~,2F ± ~,2F" (uncertain-number-value n) (uncertain-number-uncertainty n)))
(defun ~+ (n1 n2)
(let* ((value1 (uncertain-number-value n1))
(value2 (un... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Wren | Wren | var squares = (1..18).map { |i| i * i }.toList
var combs = []
var results = []
// generate combinations of the numbers 0 to n-1 taken m at a time
var combGen = Fn.new { |n, m|
var s = List.filled(m, 0)
var last = m - 1
var rc // recursive closure
rc = Fn.new { |i, next|
var j = next
wh... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #D | D | bool doChar(in bool odd, in void delegate() nothrow f=null) nothrow {
import core.stdc.stdio, std.ascii;
immutable int c = getchar;
if (!odd)
c.putchar;
if (c.isAlpha)
return doChar(odd, { c.putchar; if (f) f(); });
if (odd) {
if (f) f();
c.putchar;
}
return... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Delphi | Delphi |
program Odd_word_problem;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Console,
System.Character;
function doChar(isOdd: boolean; f: TProc = nil): Boolean;
begin
var c: char := Console.ReadKey(True).KeyChar;
if not isOdd then
Write(c);
if c.IsLetter then
exit(doChar(isOdd,
proce... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #8080_Assembly | 8080 Assembly | rawio: equ 6
org 100h
;;; Initialize RNG from keypresses
lxi d,keys
call puts
mvi b,4 ; 4*4 = 16 bytes
rndini: mvi c,4
lxi h,rnddat
rndin2: push b
push h
rndkey: call keyin ; Get key
ana a
jz rndkey
pop h
pop b
xra m ; XOR into random data
mov m,a
inx h
dcr c
jnz rndin2
dcr b
jnz rndini
lxi d,don... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
edge = 1
ruleNum = 104 # 01101000
maxGen = 9
mark = "@"
space = "."
initialState = ".@@@.@@.@.@.@.@..@.."
width = length(initialState)
delete rules
delete state
initRules(ruleNum)
initState(initialState, mark)
for (g = 0; g < maxGen; g++) {
... |
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... | #ALGOL_68 | ALGOL 68 | MODE F = PROC(LONG REAL)LONG REAL;
###############
## left rect ##
###############
PROC left rect = (F f, LONG REAL a, b, INT n) LONG REAL:
BEGIN
LONG REAL h= (b - a) / n;
LONG REAL sum:= 0;
LONG REAL x:= a;
WHILE x <= b - h DO
sum := sum + (h * f(x));
x +:= h
OD;
sum
END # left rect #... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #APL | APL | risefall←{
⍝ Determine if a number is in the sequence
inSeq←0=(+/2(<->)/10(⊥⍣¯1)⊢)
⍝ First 200 numbers
⎕←'The first 200 numbers are:'
⎕←(⊢(/⍨)inSeq¨)⍳404
⍝ 10,000,000th number
⍝ You can't just make a list that big and filter
⍝ it, because that will just get you a WS FULL.
⍝ Inste... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #AutoHotkey | AutoHotkey | limit1 := 200, limit2 := 10000000
count := 0, result1 := result1 := ""
loop{
num := A_Index
if !Rise_Fall(num)
continue
count++
if (count <= limit1)
result1 .= num . (Mod(count, 20) ? "`t" : "`n")
if (count = limit2){
result2 := num
break
}
if !mod(count, 1000... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #D | D | import std.stdio, std.math;
immutable struct GaussLegendreQuadrature(size_t N, FP=double,
size_t NBITS=50) {
immutable static double[N] lroots, weight;
alias FP[N + 1][N + 1] CoefMat;
pure nothrow @safe @nogc static this() {
static FP legendreEval(in ref ... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Groovy | Groovy | class Entity implements Serializable {
static final serialVersionUID = 3504465751164822571L
String name = 'Thingamabob'
public String toString() { return name }
}
class Person extends Entity implements Serializable {
static final serialVersionUID = -9170445713373959735L
Person() { name = 'Clement'... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Haskell | Haskell | {-# LANGUAGE DeriveGeneric #-}
module Main (main) where
import qualified Data.ByteString.Lazy as ByteString (readFile, writeFile)
import Data.Binary (Binary)
import qualified Data.Binary as Binary (decode, encode)
import GHC.Generics (Generic)
data Employee =
Manager String String
| In... |
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... | #Befunge | Befunge | 055*46*146*1->00p 36268>5\:4\:2v >\#%"O"/#:3#:+#< g48*- >1-:!#v_\1+::"O"%\"O"/v
>-#2:#\8#1`#:|#-1:-1\7_^#`g00:+<>\#%"O"/#::$#<3#$+g48*-v^\,+*+ 55!:*!!-"|":g+3<
>$ 36 26 58 49 81 36 26 10 \1-:#^\_^#:-1\+<00_@#:>#<$<
DI know an old lady who swallowed a F.|I don't know why she swallowed the 8.|Pe
rhaps she'll... |
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... | #C | C | #include <stdio.h>
static char const *animals[] = {
"fly",
"spider",
"bird",
"cat",
"dog",
"goat",
"cow",
"horse"
};
static char const *verses[] = {
"I don't know why she swallowed that fly.\nPerhaps she'll die\n",
"That wiggled and jiggled and tickled inside her",
"H... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #J | J |
NB. Use, linux.
NB. $ /usr/local/j64-801/bin/jconsole j.ijs 8 meter
UNIT2MULT =: /:~ _ ".&.>@:{:@:]`1:`]}"1<;._2@:(,&':');._2 'arshin:0.7112,centimeter:0.01,diuym:0.0254,fut:0.3048,kilometer:1000.0,liniya:0.00254,meter:1.0,milia:7467.6,piad:0.1778,sazhen:2.1336,tochka:0.000254,vershok:0.04445,versta:1066.8,'
exit... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Java | Java | public class OldRussianMeasures {
final static String[] keys = {"tochka", "liniya", "centimeter", "diuym",
"vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer",
"versta", "milia"};
final static double[] values = {0.000254, 0.00254, 0.01,0.0254,
0.04445, 0.1778, 0.3048, ... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Julia | Julia | using Makie
mesh([(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color = [:red, :green, :blue], shading = false)
|
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Kotlin | Kotlin | // Kotlin Native version 0.3
import kotlinx.cinterop.*
import opengl.*
fun paint() {
glClearColor(0.3f, 0.3f, 0.3f, 0.0f)
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
glShadeModel(GL_SMOOTH)
glLoadIdentity()
glTranslatef(-15.0f, -15.0f, 0.0f)
glBegin(GL_TRIANGLES)
glColor3f(... |
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... | #F.23 | F# | open System
[<EntryPoint>]
let main args =
let rnd = new Random()
let one_of_n n =
let rec loop i r =
if i >= n then r else
if rnd.Next(i + 1) = 0
then loop (i + 1) i
else loop (i + 1) r
loop 1 0
let test n trials =
le... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #Swift | Swift | func disjointOrder<T: Hashable>(m: [T], n: [T]) -> [T] {
let replaceCounts = n.reduce(into: [T: Int](), { $0[$1, default: 0] += 1 })
let reduced = m.reduce(into: ([T](), n, replaceCounts), {cur, el in
cur.0.append(cur.2[el, default: 0] > 0 ? cur.1.removeFirst() : el)
cur.2[el]? -= 1
})
return reduced.... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #Tcl | Tcl | proc orderDisjoint {theList theOrderList} {
foreach item $theOrderList {incr n($item)}
set is {}
set i 0
foreach item $theList {
if {[info exist n($item)] && [incr n($item) -1] >= 0} {
lappend is $i
}
incr i
}
foreach item $theOrderList i $is {lset theList $i $item}
return $theList
} |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Maple | Maple |
OptionalSort := proc(input, {
ordering :: Or(procedures,identical("lexicographic")) := "lexicographic",
column :: posint := 1,
reverse :: truefalse := false
} )
local compare;
if ordering = "lexicographic" then
compare := (x,y)->evalb(`if`(reverse,x[column]>=y[column],x[column]<=y[column])... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Options[OptionalSort]={ordering->lexicographic,column->1,reverse-> False};
OptionalSort[x_List,OptionsPattern[]]:=If[OptionValue[reverse]==True,
SortBy[x ,#[[OptionValue[column]]]&]//Reverse,
SortBy[x,#[[OptionValue[column]]]&] ]
OptionalSort[{{"a" ,"b", "c"}, {"", "q", "z"},{"zap" ,"zip", "Zot"}} ]
->{{,q,z},{a,b,c}... |
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... | #J | J | before=: -.@(-: /:~)@,&<~ |
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... | #Java | Java | import java.util.Arrays;
import java.util.List;
public class ListOrder{
public static boolean ordered(double[] first, double[] second){
if(first.length == 0) return true;
if(second.length == 0) return false;
if(first[0] == second[0])
return ordered(Arrays.copyOfRange(first, 1, first.length),
Arrays.cop... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 INPUT "How many rows? ";n
15 IF n<1 THEN GO TO 210
20 DIM c(n)
25 DIM d(n)
30 LET c(1)=1
35 LET d(1)=1
40 FOR r=1 TO n
50 FOR i=1 TO (n-r)
60 PRINT " ";
70 NEXT i
80 FOR i=1 TO r
90 PRINT c(i);" ";
100 NEXT i
110 PRINT
120 IF r>=n THEN GO TO 140
130 LET d(r+1)=1
140 FOR i=2 TO r
150 LET d(i)=c(i-1)+c(i)
... |
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... | #Smalltalk | Smalltalk | 5 + b negated. "same as 5 + (b negated); unary > binary"
a abs - b sqrt "same as (a abs) - (b sqrt); unary > binary"
a bitAnd:1+a abs. "same as a bitAnd:(1+(a abs)); unary > binary > keyword"
(a bitAnd:1+a) bitOr:(b bitAnd:1+2 abs). "ditto"
"Beginners might be confused by:... |
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... | #Standard_ML | Standard ML | -2^2=-(2^2)=-4
2^3^2=(2^3)^2=64
4/2π=(4/2)π=2π=6.283185307
-B/2A=-((B/2)*A)=-(B/2)*A
|
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... | #Tcl | Tcl | -2^2=-(2^2)=-4
2^3^2=(2^3)^2=64
4/2π=(4/2)π=2π=6.283185307
-B/2A=-((B/2)*A)=-(B/2)*A
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Io | Io | file := File clone openForReading("./unixdict.txt")
words := file readLines
file close
maxLen := 0
orderedWords := list()
words foreach(word,
if( (word size >= maxLen) and (word == (word asMutable sort)),
if( word size > maxLen,
maxLen = word size
orderedWords empty
)
... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Pike | Pike | int main(){
if(pal("rotator")){
write("palindrome!\n");
}
if(!pal("asdf")){
write("asdf isn't a palindrome.\n");
}
}
int pal(string input){
if( reverse(input) == input ){
return 1;
} else {
return 0;
}
} |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #D | D | import std.stdio, std.math, std.string, std.typecons, std.traits;
const struct Imprecise {
private const double value, delta;
this(in double v, in double d) pure nothrow {
this.value = v;
this.delta = abs(d);
}
enum IsImprecise(T) = is(Unqual!T == Unqual!(typeof(this)));
I re... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #EchoLisp | EchoLisp |
(lib 'sequences)
(define input-stream null)
(define output-stream "")
;;---------------------------
;; character I/O simulation
;; --------------------------
(define (read-char) (next input-stream)) ;; #f if EOF
(define (write-char c) (when c (set! output-stream (string-append output-stream c))))
(define (init-st... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #11l | 11l | V data = Array(‘139275486’)
V trials = 0
L data != sorted(data)
trials++
V flip = Int(input(‘###2: LIST: '#.' Flip how many?: ’.format(trials, data.join(‘ ’))))
data.reverse_range(0 .< flip)
print("\nYou took #. attempts to put the digits in order!".format(trials)) |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #11l | 11l | F f([Int]? &a)
I a != N
a.append(1)
f(N)
[Int] arr
f(&arr)
print(arr) |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #BASIC | BASIC | DECLARE FUNCTION life$ (lastGen$)
DECLARE FUNCTION getNeighbors! (group$)
CLS
start$ = "_###_##_#_#_#_#__#__"
numGens = 10
FOR i = 0 TO numGens - 1
PRINT "Generation"; i; ": "; start$
start$ = life$(start$)
NEXT i
FUNCTION getNeighbors (group$)
ans = 0
IF (MID$(group$, 1, 1) = "#") THEN ans = ans + 1
IF (MID$... |
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... | #ALGOL_W | ALGOL W | begin % compare some numeric integration methods %
long real procedure leftRect ( long real procedure f
; long real value a, b
; integer value n
) ;
begin
long real ... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #AWK | AWK |
# syntax: GAWK -f NUMBERS_WITH_EQUAL_RISES_AND_FALLS.AWK
# converted from Go
BEGIN {
print("1-200:")
while (1) {
if (rises_equals_falls(++n)) {
if (++count <= 200) {
printf("%4d",n)
if (count % 20 == 0) {
printf("\n")
}
}
if (count == 1E7... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #C | C | #include <stdio.h>
/* Check whether a number has an equal amount of rises
* and falls
*/
int riseEqFall(int num) {
int rdigit = num % 10;
int netHeight = 0;
while (num /= 10) {
netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
rdigit = num % 10;
}
return netHeight == 0;... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #Delphi | Delphi | program Legendre;
{$APPTYPE CONSOLE}
const Order = 5;
Epsilon = 1E-12;
var Roots : array[0..Order-1] of double;
Weight : array[0..Order-1] of double;
LegCoef : array [0..Order,0..Order] of double;
function F(X:double) : double;
begin
Result := Exp(X);
end;
procedure PrepCoef;
var I, N : i... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #J | J | lin_z_=:5!:5
serializeObject=:3 :0
p=. copath y
d=. ;LF;"1(,'=:';lin__y)"0 nl__y i.4
'(',(5!:5<'p'),')(copath[cocurrent@])cocreate ''''',,d,LF
)
deserializeObject=:3 :0
o=.conl 1
0!:100 y
(conl 1)-.o
)
coclass'room'
create=:3 :'size=:y'
print=:3 :'''room size '',":size'
coclass'kitchen'
coinsert... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Java | Java | import java.io.*;
// classes must implement java.io.Serializable in order to be serializable
class Entity implements Serializable {
// it is recommended to hard-code serialVersionUID so changes to class
// will not invalidate previously serialized objects
static final long serialVersionUID = 3504465751164... |
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... | #C.23 | C# | using System;
namespace OldLady
{
internal class Program
{
private const string reason = "She swallowed the {0} to catch the {1}";
private static readonly string[] creatures = {"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"};
private static readonly string[] comments =... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Julia | Julia | using DataStructures
const unit2mult = Dict(
"arshin" => 0.7112, "centimeter" => 0.01, "diuym" => 0.0254,
"fut" => 0.3048, "kilometer" => 1000.0, "liniya" => 0.00254,
"meter" => 1.0, "milia" => 7467.6, "piad" => 0.1778,
"sazhen" => 2.1336, "tochka" => 0.000254, "vershok"... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Kotlin | Kotlin | // version 1.0.6
/* clears console on Windows 10 */
fun cls() = ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor()
fun main(args: Array<String>) {
val units = listOf("tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Liberty_BASIC | Liberty BASIC | nomainwin
struct rect, x as long, y as long, x2 as long, y2 as long
struct PFD, Size as word, Version as word, Flags as long,_
PixelType as char[1], ColorBits as char[1], RedBits as char[1],_
RedShift as char[1], GreenBits as char[1], GreenShift as char[1],_
BlueBits as char[1], BlueSh... |
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... | #Factor | Factor | ! rosettacode/random-line/random-line.factor
USING: io kernel locals math random ;
IN: rosettacode.random-line
:: random-line ( -- line )
readln :> choice! 1 :> count!
[ readln dup ]
[ count 1 + dup count! random zero?
[ choice! ] [ drop ] if
] while drop
choice ; |
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... | #Forth | Forth | require random.fs
: frnd
rnd 0 d>f [ s" MAX-U" environment? drop 0 d>f 1/f ] fliteral f* ;
: u>f 0 d>f ;
: one_of_n ( u1 -- u2 )
1 swap 1+ 2 ?do frnd i u>f 1/f f< if drop i then loop ;
create hist 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , does> swap cells + ;
: simulate 1000000 0 do 1 10 one_of_n 1- h... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #Wren | Wren | import "/fmt" for Fmt
var NULL = "\0"
var orderDisjointList = Fn.new { |m, n|
var nList = n.split(" ")
// first replace the first occurrence of items of 'n' in 'm' with the NULL character
// which we can safely assume won't occur in 'm' naturally
for (item in nList) {
var ix = m.indexOf(ite... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Nemerle | Nemerle | Sorter (table : list[list[string]], ordering = "lexicographic", column = 0, reverse = false) : list[list[string]]
{
// implementation goes here
} |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Nim | Nim | import algorithm, strutils, sugar
proc printTable(a: seq[seq[string]]) =
for row in a:
for x in row: stdout.write x, repeat(' ', 4 - x.len)
echo ""
echo ""
proc sortTable(a: seq[seq[string]], column = 0, reverse = false,
ordering: (proc(a,b: string): int) = system.cmp) : seq[seq[string]] =
let ord... |
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... | #JavaScript | JavaScript | (() => {
'use strict';
// <= is already defined for lists in JS
// compare :: [a] -> [a] -> Bool
const compare = (xs, ys) => xs <= ys;
// TEST
return [
compare([1, 2, 1, 3, 2], [1, 2, 0, 4, 4, 0, 0, 0]),
compare([1, 2, 0, 4, 4, 0, 0, 0], [1, 2, 1, 3, 2])
];
// -... |
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... | #TI-83_BASIC | TI-83 BASIC | -2^2=-(2^2)=-4
2^3^2=(2^3)^2=64
4/2π=(4/2)π=2π=6.283185307
-B/2A=-((B/2)*A)=-(B/2)*A
|
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... | #VBScript | VBScript | -2^2=(-2)^2=4
2^3^2=(2^3)^2=64
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #J | J | require'web/gethttp'
dict=: gethttp'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
oWords=: (#~ ] = /:~L:0) <;._2 dict-.CR
;:inv (#~ (= >./)@:(#@>))oWords
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Java | Java | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Ordered {
private static boolean isOrderedWord(String word){
char[] sortedWord... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #PL.2FI | PL/I | is_palindrome = (text = reverse(text)); |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #F.23 | F# | let sqr (x : float) = x * x
let abs (x : float) = System.Math.Abs x
let pow = System.Math.Pow
type Approx (value : float, sigma : float) =
member this.value = value
member this.sigma = sigma
static member (~-) (x : Approx) = Approx (- x.value, x.sigma)
static member (%+) (x: Approx, y : float) = Ap... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Elixir | Elixir | defmodule Odd_word do
def handle(s, false, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do
o.(s)
handle(i.(), false, i, o)
end
def handle(s, t, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do
d = handle(i.(), :rec, i, o)
o.(s)
if t == true, do: handle(d, t... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Erlang | Erlang |
handle(S, false, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) ->
O(S),
handle(I(), false, I, O);
handle(S, T, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) ->
D = handle(I(), rec, I, O),
O(S),
case T of true -> handle(D, T, I, O); _ -> D end;
handle(S, ... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #Action.21 | Action! | PROC KnuthShuffle(BYTE ARRAY tab BYTE size)
BYTE i,j,tmp
i=size-1
WHILE i>0
DO
j=Rand(i+1)
tmp=tab(i)
tab(i)=tab(j)
tab(j)=tmp
i==-1
OD
RETURN
BYTE FUNC IsSorted(BYTE ARRAY tab BYTE size)
BYTE i
FOR i=0 TO size-2
DO
IF tab(i)>tab(i+1) THEN
RETURN (0)
FI
OD
RETUR... |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #8th | 8th |
null? if "item was null" . then
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program nullobj64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM6... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #BASIC256 | BASIC256 | arraybase 1
dim start = {0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0}
dim sgtes(start[?]+1)
for k = 0 to 9
print "Generation "; k; ": ";
for j = 0 to start[?]-1
if start[j] then print "#"; else print "_";
if start[j-1] + start[j] + start[j+1] = 2 then sgtes[j] = 1 else sgtes[j] = 0
next j
... |
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... | #AutoHotkey | AutoHotkey | MsgBox % Rect("fun", 0, 1, 10,-1) ; 0.45 left
MsgBox % Rect("fun", 0, 1, 10) ; 0.50 mid
MsgBox % Rect("fun", 0, 1, 10, 1) ; 0.55 right
MsgBox % Trapez("fun", 0, 1, 10) ; 0.50
MsgBox % Simpson("fun", 0, 1, 10) ; 0.50
Rect(f,a,b,n,side=0) { ; side: -1=left, 0=midpoint, 1=right
h := (b - a) / n
sum := 0, a += ... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
bool equal_rises_and_falls(int n) {
int total = 0;
for (int previous_digit = -1; n > 0; n /= 10) {
int digit = n % 10;
if (previous_digit > digit)
++total;
else if (previous_digit >= 0 && previous_digit < digit)
--total;
... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #CLU | CLU | % Find how many rises and falls a number has
rises_falls = proc (n: int) returns (int,int)
rises: int := 0
falls: int := 0
while n >= 10 do
dl: int := n//10
n := n / 10
dh: int := n//10
if dh < dl then rises := rises + 1
elseif dl < dh then falls := falls + 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.