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/Hofstadter-Conway_$10,000_sequence | Hofstadter-Conway $10,000 sequence | The definition of the sequence is colloquially described as:
Starting with the list [1,1],
Take the last number in the list so far: 1, I'll call it x.
Count forward x places from the beginning of the list to find the first number to add (1)
Count backward x places from the end of the list to find the secon... | #Oz | Oz | declare
local
Cache = {Dictionary.new}
Cache.1 := 1
Cache.2 := 1
in
fun {A N}
if {Not {Dictionary.member Cache N}} then
Cache.N := {A {A N-1}} + {A N-{A N-1}}
end
Cache.N
end
end
Float = Int.toFloat
for I in 0..19 do
Range = {List.number {Po... |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #jq | jq | jq -n —-arg s 'Goodbye, World!' '$s | stderr | empty' |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Julia | Julia | println(STDERR, "Goodbye, World!") |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Kotlin | Kotlin | fun main(args: Array<String>) {
System.err.println("Goodbye, World!")
} |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #langur | langur | writelnErr "goodbye, people" |
http://rosettacode.org/wiki/Hofstadter_Q_sequence | Hofstadter Q sequence | Hofstadter Q sequence
Q
(
1
)
=
Q
(
2
)
=
1
,
Q
(
n
)
=
Q
(
n
−
Q
(
n
−
1
)
)
+
Q
(
n
−
Q
(
n
−
2
)
)
,
n
>
2.
{\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}}
It is defined like the Fibonacc... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
// task
for n := 1; n <= 10; n++ {
... |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #Tcl | Tcl | package require math::bigfloat
namespace import math::bigfloat::*
# Precision is an arbitrary value large enough to provide clear demonstration
proc hickerson {n {precision 28}} {
set fac 1
for {set i 1} {$i <= $n} {incr i} {set fac [expr {$fac * $i}]}
set numerator [int2float $fac $precision]
set 2 [... |
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
| #Action.21 | Action! | Proc Main()
Print("Hello world!")
Return |
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... | #J | J | a=: 0&{"1
b=: 1&{"1
c=: 2&{"1
s=: (a+b+c) % 2:
area=: 2 %: s*(s-a)*(s-b)*(s-c) NB. Hero's formula
perim=: +/"1
isPrimHero=: (0&~: * (= <.@:+))@area * 1 = a +. b +. c |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #C.2B.2B | C++ |
// Use <functional> for C++11
#include <tr1/functional>
#include <iostream>
using namespace std;
using namespace std::tr1;
void first(function<void()> f)
{
f();
}
void second()
{
cout << "second\n";
}
int main()
{
first(second);
}
|
http://rosettacode.org/wiki/Hello_world/Web_server | Hello world/Web server | The browser is the new GUI !
Task
Serve our standard text Goodbye, World! to http://localhost:8080/ so that it can be viewed with a web browser.
The provided solution must start or implement a server that accepts multiple client connections and serves text as requested.
Note that starting a web browser or... | #Liberty_BASIC | Liberty BASIC | print "hello world!" |
http://rosettacode.org/wiki/Hello_world/Web_server | Hello world/Web server | The browser is the new GUI !
Task
Serve our standard text Goodbye, World! to http://localhost:8080/ so that it can be viewed with a web browser.
The provided solution must start or implement a server that accepts multiple client connections and serves text as requested.
Note that starting a web browser or... | #Lua | Lua | local socket = require "socket"
local headers = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Length: %d\r\n\r\n%s"
local content = "<!doctype html><html><title>Goodbye, World!</title><h1>Goodbye, World!"
local server = assert(socket.bind("localhost", 8080))
repeat
local client = server:accep... |
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 ... | #Run_BASIC | Run BASIC | text$ ="
<<'FOO'
Now
is
the
time
for
all
good mem
to come to the aid of their country."
print text$ |
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 ... | #Rust | Rust | let x = r#"
This is a "raw string literal," roughly equivalent to a heredoc.
"#;
let y = r##"
This string contains a #.
"##;
|
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 ... | #Scala | Scala | object temp {
val MemoriesOfHolland=
"""Thinking of Holland
|I see broad rivers
|slowly chuntering
|through endless lowlands,
|rows of implausibly
|airy poplars
|standing like tall plumes
|against the horizon;
|and sunk in the unbounded
|vastness of space
|homesteads and boweri... |
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 ... | #SenseTalk | SenseTalk |
set script to {{SCRIPT
put "Script demonstrating block quotes"
set text to {{
"I wish it need not have happened in my time," said Frodo.
"So do I," said Gandalf, "and so do all who live to see such times. But that is not for them to decide. All we have to decide is what to do with the time that is given us."
}}
p... |
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 ... | #SequenceL | SequenceL | main :=
"In SequenceL
strings are
multiline
by default.
'All' non-\"
characters are
valid for inclusion
in a string."; |
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences | Hofstadter Figure-Figure sequences | These two sequences of positive integers are defined as:
R
(
1
)
=
1
;
S
(
1
)
=
2
R
(
n
)
=
R
(
n
−
1
)
+
S
(
n
−
1
)
,
n
>
1.
{\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}}
The sequence
S
(
n
)
{\displaystyle S(n)}
is further... | #Python | Python | def ffr(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return ffr.r[n]
except IndexError:
r, s = ffr.r, ffs.s
ffr_n_1 = ffr(n-1)
lastr = r[-1]
# extend s up to, and one past, last r
s += list(range(s[-1] + 1, lastr))
if... |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #ooRexx | ooRexx | /* Rexx ---------------------------------------------------------------
* 04.03.2014 Walter Pachl
*--------------------------------------------------------------------*/
c = .array~of(-19,7,-4,6) -- coefficients of all x^0..x^n in order
n=3
x=3
r=0
loop i=n+1 to 1 by -1
r=r*x+c[i]
End
Say r
Say 6*x**3-4*x**2+7*x-19 |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #Oz | Oz | declare
fun {Horner Coeffs X}
{FoldL1 {Reverse Coeffs}
fun {$ Acc Coeff}
Acc*X + Coeff
end}
end
fun {FoldL1 X|Xr Fun}
{FoldL Xr Fun X}
end
in
{Show {Horner [~19 7 ~4 6] 3}} |
http://rosettacode.org/wiki/Hilbert_curve | Hilbert curve |
Task
Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
| #Racket | Racket | #lang racket
(require racket/draw)
(define rules '([A . (- B F + A F A + F B -)]
[B . (+ A F - B F B - F A +)]))
(define (get-cmds n cmd)
(cond
[(= 0 n) (list cmd)]
[else (append-map (curry get-cmds (sub1 n))
(dict-ref rules cmd (list cmd)))]))
(define (make-curve... |
http://rosettacode.org/wiki/Hilbert_curve | Hilbert curve |
Task
Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
| #Raku | Raku | use SVG;
role Lindenmayer {
has %.rules;
method succ {
self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
}
}
my $hilbert = 'A' but Lindenmayer( { A => '-BF+AFA+FB-', B => '+AF-BFB-FA+' } );
$hilbert++ xx 7;
my @points = (647, 13);
for $hilbert.comb {
state ($x, $y) = ... |
http://rosettacode.org/wiki/Holidays_related_to_Easter | Holidays related to Easter | Task
Calculate the dates of:
Easter
Ascension Thursday
Pentecost
Trinity Sunday
Corpus Christi feast (for Catholic)
All Saints' Sunday (for Orthodox)
As an example, calculate for the first year of each century from;
years 400 to 2100 CE and for
years 2010 to 2020 CE.
Note
... | #Nim | Nim | import strformat, strutils, times
const HolidayOffsets = {"Easter": 0, "Ascension": 39, "Pentecost": 49,
"Trinity": 56, "C/Christi": 60}
proc easterDate(year: int): DateTime =
let a = year mod 19
let b = year div 100
let c = year mod 100
let d = b div 4
let e = b mod 4
let f = ... |
http://rosettacode.org/wiki/Horizontal_sundial_calculations | Horizontal sundial calculations | Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit... | #Perl | Perl | use utf8;
binmode STDOUT, ":utf8";
use constant π => 3.14159265;
sub d2r { $_[0] * π / 180 } # degrees to radians
sub r2d { $_[0] * 180 / π } # radians to degrees
print 'Enter latitude => '; $latitude = <>;
print 'Enter longitude => '; $longitude = <>;
print 'Enter legal meridian => '; $meridian = <>... |
http://rosettacode.org/wiki/Huffman_coding | Huffman coding | Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols.
For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi... | #Quackery | Quackery | [ 2dup peek 1+ unrot poke ] is itemincr ( [ n --> [ )
[ [ 0 128 of ] constant
swap witheach itemincr
' [ i^ join ] map
' [ 0 peek ] filter ] is countchars ( $ --> [ )
[ 0 peek dip [ 0 peek ] < ] is fewerchars ( [ [ --> b )
[ behead rot
behead rot + un... |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Standard_ML | Standard ML | val eye= fn n => List.tabulate( n, fn i => List.tabulate( n, fn j=> if j=i then 1.0 else 0.0)); |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Stata | Stata | . mat a = I(3)
. mat list a
symmetric a[3,3]
c1 c2 c3
r1 1
r2 0 1
r3 0 0 1 |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #SQL_PL | SQL PL |
CREATE TABLE TEST (
VAL1 INT,
VAL2 INT
);
INSERT INTO TEST (VAL1, VAL2) VALUES
(1, 2),
(2, 2),
(2, 1);
SELECT
CASE
WHEN VAL1 < VAL2 THEN VAL1 || ' less than ' || VAL2
WHEN VAL1 = VAL2 THEN VAL1 || ' equal to ' || VAL2
WHEN VAL1 > VAL2 THEN VAL1 || ' greater than ' || VAL2
END COMPARISON
F... |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #SSEM | SSEM | accumulator := a - b;
if accumulator >= 0 then
(* a is not less than b, so *)
goto next_test
else
goto less;
next_test: accumulator := accumulator - 1;
if accumulator >= 0 then
goto greater
else
... |
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.
| #Jsish | Jsish | #!/usr/bin/env jsish
function httpGet(fileargs:array|string, conf:object=void) {
var options = { // Web client for downloading files from url
headers : [], // Header fields to send.
nowait : false, // Just return object: caller will call update.
onDone : null... |
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence | Hofstadter-Conway $10,000 sequence | The definition of the sequence is colloquially described as:
Starting with the list [1,1],
Take the last number in the list so far: 1, I'll call it x.
Count forward x places from the beginning of the list to find the first number to add (1)
Count backward x places from the end of the list to find the secon... | #PARI.2FGP | PARI/GP | HC(n)=my(a=vectorsmall(n));a[1]=a[2]=1;for(i=3,n,a[i]=a[a[i-1]]+a[i-a[i-1]]);a;
maxima(n)=my(a=HC(1<<n),m);vector(n-1,k,m=0;for(i=1<<k+1,1<<(k+1)-1,m=max(m,a[i]/i));m);
forstep(i=#a,1,-1,if(a[i]/i>=.55,return(i))) |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Lasso | Lasso | define stderr(s::string) => {
file_stderr->writeBytes(#s->asBytes)
}
stderr('Goodbye, World!') |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Lingo | Lingo | -- print to standard error
stdErr("Goodbye, World!", TRUE)
-- print to the Windows debug console (shown in realtime e.g. in Systernal's DebugView)
dbgPrint("Goodbye, World!") |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #LLVM | LLVM | ; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such ... |
http://rosettacode.org/wiki/Hofstadter_Q_sequence | Hofstadter Q sequence | Hofstadter Q sequence
Q
(
1
)
=
Q
(
2
)
=
1
,
Q
(
n
)
=
Q
(
n
−
Q
(
n
−
1
)
)
+
Q
(
n
−
Q
(
n
−
2
)
)
,
n
>
2.
{\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}}
It is defined like the Fibonacc... | #Go | Go | package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
// task
for n := 1; n <= 10; n++ {
... |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #TI-83_BASIC | TI-83 BASIC | For(N,1,17
N!/(2ln(2)^(N+1→H
Disp N,H,"IS
round(H,1)-iPart(H)
If not(Ans=.9 or not(Ans
Disp "NOT
Disp "ALMOST INTEGER
End |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
import "/big" for BigInt
var hickerson = Fn.new { |n|
var fact = BigInt.new(Int.factorial(n)) // accurate up to n == 18
var ln2 = BigInt.new("693147180559945309417232121458176568075500134360255254120680009") // 63 digits
var mult = BigInt.new("1e64").pow(n+1) ... |
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
| #ActionScript | ActionScript | trace("Hello world!"); |
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... | #Java | Java | import java.util.ArrayList;
public class Heron {
public static void main(String[] args) {
ArrayList<int[]> list = new ArrayList<>();
for (int c = 1; c <= 200; c++) {
for (int b = 1; b <= c; b++) {
for (int a = 1; a <= b; a++) {
if (gcd(gcd(a, b),... |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #Clean | Clean | map f [x:xs] = [f x:map f xs]
map f [] = [] |
http://rosettacode.org/wiki/Hello_world/Web_server | Hello world/Web server | The browser is the new GUI !
Task
Serve our standard text Goodbye, World! to http://localhost:8080/ so that it can be viewed with a web browser.
The provided solution must start or implement a server that accepts multiple client connections and serves text as requested.
Note that starting a web browser or... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | listener =
SocketListen["127.0.0.1:8080",
Function[{assoc},
With[{client = assoc["SourceSocket"]},
WriteString[client,
"HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"];
Close[client]]]]
SystemOpen["http://127.0.0.1:8080"] |
http://rosettacode.org/wiki/Hello_world/Web_server | Hello world/Web server | The browser is the new GUI !
Task
Serve our standard text Goodbye, World! to http://localhost:8080/ so that it can be viewed with a web browser.
The provided solution must start or implement a server that accepts multiple client connections and serves text as requested.
Note that starting a web browser or... | #Modula-2 | Modula-2 |
MODULE access;
FROM InOut IMPORT WriteString, WriteLn;
BEGIN
WriteString ("Content-Type : text/plain");
WriteLn;
WriteLn;
WriteString ("Hello web wide world.");
WriteLn
END access.
|
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 ... | #Sidef | Sidef | var text = <<"EOF";
a = #{1+2}
b = #{3+4}
EOF |
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 ... | #SQL_PL | SQL PL |
db2 "select 'This is the first line.
This is the second line.
This is the third line.' from sysibm.sysdummy1"
|
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 ... | #Tcl | Tcl | set hereDocExample {
In Tcl, the {curly brace} notation is strictly a here-document style notation
as it permits arbitrary content inside it *except* for an unbalanced brace.
That is typically not a problem as seen in reality, as almost all content that
might be placed in a here-doc is either brace-free or balanced.
T... |
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 ... | #TXR | TXR | #!/usr/bin/txr -f
@(maybe)
@(bind USER "Unknown User")
@(or)
@(bind MB "???")
@(end)
@(output)
Dear @USER
Your are over your disk quota by @MB megabytes.
The Computer
@(end) |
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 ... | #UNIX_Shell | UNIX Shell | #!/bin/sh
cat << ANARBITRARYTOKEN
The river was deep but I swam it, Janet.
The future is ours so let's plan it, Janet.
So please don't tell me to can it, Janet.
I've one thing to say and that's ...
Dammit. Janet, I love you.
ANARBITRARYTOKEN |
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences | Hofstadter Figure-Figure sequences | These two sequences of positive integers are defined as:
R
(
1
)
=
1
;
S
(
1
)
=
2
R
(
n
)
=
R
(
n
−
1
)
+
S
(
n
−
1
)
,
n
>
1.
{\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}}
The sequence
S
(
n
)
{\displaystyle S(n)}
is further... | #R | R | rValues <- 1
sValues <- 2
ffr <- function(n)
{
if(!is.na(rValues[n])) rValues[n] else (rValues[n] <<- ffr(n-1) + ffs(n-1))
}
#In theory, generating S requires computing ALL values not in R.
#That would be infinitely many values.
#However, to generate S(n) we only need to observe that its value cannot exceed R(n)+1.... |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #PARI.2FGP | PARI/GP | horner(v,x)={
my(s=0);
forstep(i=#v,1,-1,s=s*x+v[i]);
s
}; |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #Pascal | Pascal | Program HornerDemo(output);
function horner(a: array of double; x: double): double;
var
i: integer;
begin
horner := a[high(a)];
for i := high(a) - 1 downto low(a) do
horner := horner * x + a[i];
end;
const
poly: array [1..4] of double = (-19.0, 7.0, -4.0, 6.0);
begin
write ('Horner cal... |
http://rosettacode.org/wiki/Hilbert_curve | Hilbert curve |
Task
Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
| #Ring | Ring |
# Project : Hilbert curve
load "guilib.ring"
paint = null
x1 = 0
y1 = 0
new qapp
{
win1 = new qwidget() {
setwindowtitle("Hilbert curve")
setgeometry(100,100,400,500)
label1 = new qlabel(win1) {
setgeometry(10,1... |
http://rosettacode.org/wiki/Hilbert_curve | Hilbert curve |
Task
Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
| #Ruby | Ruby |
# frozen_string_literal: true
load_library :grammar
attr_reader :hilbert
def settings
size 600, 600
end
def setup
sketch_title '2D Hilbert'
@hilbert = Hilbert.new
hilbert.create_grammar 5
no_loop
end
def draw
background 0
hilbert.render
end
Turtle = Struct.new(:x, :y, :theta)
# Hilbert Class h... |
http://rosettacode.org/wiki/Holidays_related_to_Easter | Holidays related to Easter | Task
Calculate the dates of:
Easter
Ascension Thursday
Pentecost
Trinity Sunday
Corpus Christi feast (for Catholic)
All Saints' Sunday (for Orthodox)
As an example, calculate for the first year of each century from;
years 400 to 2100 CE and for
years 2010 to 2020 CE.
Note
... | #PARI.2FGP | PARI/GP | /*
* Normalized Julian Day Number from date (base 1899-12-30 00:00:00)
* D = Vec [year, month, day]
* return day number
*/
njd(D) =
{
my (m, y);
if (D[2] > 2, y = D[1]; m = D[2] + 1, y = D[1] - 1; m = D[2] + 13);
(1461 * y) \ 4 + (306001 * m) \ 10000 + D[3] - 694024
/* Calendar reform ? */
+ if (100... |
http://rosettacode.org/wiki/Horizontal_sundial_calculations | Horizontal sundial calculations | Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit... | #Phix | Phix | with javascript_semantics
function prompt(string text, atom v)
if platform()!=JS then
printf(1,"Enter %s (%g):",{text,v})
object answer = gets(0)
puts(1, '\n')
if string(answer) then
v = to_number(trim(answer),v)
end if
else
printf(1,"%s:%g\n",{text,v}... |
http://rosettacode.org/wiki/Huffman_coding | Huffman coding | Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols.
For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi... | #Racket | Racket |
#lang racket
(require data/heap
data/bit-vector)
;; A node is either an interior, or a leaf.
;; In either case, they record an item with an associated frequency.
(struct node (freq) #:transparent)
(struct interior node (left right) #:transparent)
(struct leaf node (val) #:transparent)
;; node<=?: node ... |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Swift | Swift | func identityMatrix(size: Int) -> [[Int]] {
return (0..<size).map({i in
return (0..<size).map({ $0 == i ? 1 : 0})
})
}
print(identityMatrix(size: 5)) |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Tailspin | Tailspin |
templates identityMatrix
def n: $;
[1..$n -> [1..~$ -> 0, 1, $~..$n -> 0]] !
end identityMatrix
def identity: 5 -> identityMatrix;
$identity... -> '|$(1);$(2..last)... -> ', $;';|
' -> !OUT::write
|
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Standard_ML | Standard ML | fun compare_integers(a, b) =
if a < b then print "A is less than B\n"
if a > b then print "A is greater than B\n"
if a = b then print "A equals B\n"
fun test () =
let
open TextIO
val SOME a = Int.fromString (input stdIn)
val SOME b = Int.fromString (input stdIn)
in
compare_integers (a, b)
... |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Swift | Swift | import Cocoa
var input = NSFileHandle.fileHandleWithStandardInput()
println("Enter two integers separated by a space: ")
let data = input.availableData
let stringArray = NSString(data: data, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ")
var a:Int!
var b:Int!
if (stringArray?.count == 2) {
... |
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.
| #Julia | Julia | readurl(url) = open(readlines, download(url))
readurl("http://rosettacode.org/index.html") |
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.
| #Kotlin | Kotlin | // version 1.1.2
import java.net.URL
import java.io.InputStreamReader
import java.util.Scanner
fun main(args: Array<String>) {
val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
val isr = InputStreamReader(url.openStream())
val sc = Scanner(isr)
while (sc.hasNextLine()) println(sc.n... |
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence | Hofstadter-Conway $10,000 sequence | The definition of the sequence is colloquially described as:
Starting with the list [1,1],
Take the last number in the list so far: 1, I'll call it x.
Count forward x places from the beginning of the list to find the first number to add (1)
Count backward x places from the end of the list to find the secon... | #Pascal | Pascal |
program HofStadterConway;
const
Pot2 = 20;// tested with 30 -> 4 GB;
type
tfeld = array[0..1 shl Pot2] of LongWord;
tpFeld = ^tFeld;
tMaxPos = record
mpMax : double;
mpValue,
mpPos : longWord;
end;
tArrMaxPos = array[0..Pot2-1] of tMaxPos;
var
a : tpFe... |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Logtalk | Logtalk |
:- object(error_message).
% the initialization/1 directive argument is automatically executed
% when the object is compiled and loaded into memory:
:- initialization(write(user_error, 'Goodbye, World!\n')).
:- end_object.
|
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Lua | Lua | io.stderr:write("Goodbye, World!\n") |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #m4 | m4 | errprint(`Goodbye, World!
')dnl |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #MANOOL | MANOOL | {{extern "manool.org.18/std/0.3/all"} in Err.WriteLine["Goodbye, World!"]} |
http://rosettacode.org/wiki/Hofstadter_Q_sequence | Hofstadter Q sequence | Hofstadter Q sequence
Q
(
1
)
=
Q
(
2
)
=
1
,
Q
(
n
)
=
Q
(
n
−
Q
(
n
−
1
)
)
+
Q
(
n
−
Q
(
n
−
2
)
)
,
n
>
2.
{\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}}
It is defined like the Fibonacc... | #GW-BASIC | GW-BASIC | 10 DIM Q!(1000)
20 Q(1) = 1: Q(2) = 1
30 FOR N = 3 TO 1000
40 Q(N) = Q(N - Q(N - 1)) + Q(N - Q(N - 2))
50 NEXT N
60 FOR N = 1 TO 10
70 PRINT Q(N)
80 NEXT N
90 PRINT Q(1000) |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #zkl | zkl | var [const] BN=Import("zklBigNum"),
X =BN("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
ln2X=BN("693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687")
;
fcn hickerson(n){ BN(n).factorial()*X.pow(n+1)*10... |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
Put_Line ("Hello world!");
end Main; |
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... | #JavaScript | JavaScript |
window.onload = function(){
var list = [];
var j = 0;
for(var c = 1; c <= 200; c++)
for(var b = 1; b <= c; b++)
for(var a = 1; a <= b; a++)
if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c)))
list[j++] = new Array(a, b, c, a + b + c, heronArea(a, b, c));
... |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #Clojure | Clojure |
(defn append-hello [s]
(str "Hello " s))
(defn modify-string [f s]
(f s))
(println (modify-string append-hello "World!"))
|
http://rosettacode.org/wiki/Hello_world/Web_server | Hello world/Web server | The browser is the new GUI !
Task
Serve our standard text Goodbye, World! to http://localhost:8080/ so that it can be viewed with a web browser.
The provided solution must start or implement a server that accepts multiple client connections and serves text as requested.
Note that starting a web browser or... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
class RHelloWorldWebServer public
properties public constant
isTrue = boolean (1 == 1)
isFalse = boolean (1 \== 1)
greeting1 = "Goodbye, World!"
greeting2 = '' -
|| 'HTTP/1.1 200 OK\r\n' -
|| 'Content-Type: text... |
http://rosettacode.org/wiki/Hello_world/Web_server | Hello world/Web server | The browser is the new GUI !
Task
Serve our standard text Goodbye, World! to http://localhost:8080/ so that it can be viewed with a web browser.
The provided solution must start or implement a server that accepts multiple client connections and serves text as requested.
Note that starting a web browser or... | #Nim | Nim | import asynchttpserver, asyncdispatch
proc cb(req: Request) {.async.} =
await req.respond(Http200, "Hello, World!")
asyncCheck newAsyncHttpServer().serve(Port(8080), cb)
runForever()
|
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 ... | #Ursala | Ursala | hd =
-[
The text enclosed within the so called dash-brackets shown above
and below will be interpreted as a list of character strings. It
can contain anything except uninterpreted dash-brackets, and can
be used in any declaration or expression. The dash-brackets don't
have to be on a line by themselves.
]-
examp... |
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 ... | #VBScript | VBScript |
'Purpose: Converts TXT files into VBS code with a function that returns a text string with the contents of the TXT file
' The TXT file can even be another VBS file.
'History:
' 1.0 8may2009 Initial release
'
'
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TristateUseDefault = -... |
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 ... | #Vlang | Vlang | fn main() {
m := ' leading spaces
and blank lines'
println(m)
} |
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 ... | #Wren | Wren | var a = 42
var b = """
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(a) is also interpreted literally.
`Have fun!`
"""
System.print(b) |
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 ... | #XPL0 | XPL0 | code Text=12;
Text(0, " ^"Heredocs^" are pretty much automatic. Multiple lines and
whitespace, such as indentations, are output exactly as written. Quote
marks (^") and any carets (^^) within the string must be escaped.") |
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences | Hofstadter Figure-Figure sequences | These two sequences of positive integers are defined as:
R
(
1
)
=
1
;
S
(
1
)
=
2
R
(
n
)
=
R
(
n
−
1
)
+
S
(
n
−
1
)
,
n
>
1.
{\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}}
The sequence
S
(
n
)
{\displaystyle S(n)}
is further... | #Racket | Racket | #lang racket/base
(define r-cache (make-hash '((1 . 1) (2 . 3) (3 . 7))))
(define s-cache (make-hash '((1 . 2) (2 . 4) (3 . 5) (4 . 6))))
(define (extend-r-s!)
(define r-count (hash-count r-cache))
(define s-count (hash-count s-cache))
(define last-r (ffr r-count))
(define new-r (+ (ffr r-count) (ffs r-coun... |
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences | Hofstadter Figure-Figure sequences | These two sequences of positive integers are defined as:
R
(
1
)
=
1
;
S
(
1
)
=
2
R
(
n
)
=
R
(
n
−
1
)
+
S
(
n
−
1
)
,
n
>
1.
{\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}}
The sequence
S
(
n
)
{\displaystyle S(n)}
is further... | #Raku | Raku | my %r = 1 => 1;
my %s = 1 => 2;
sub ffr ($n) { %r{$n} //= ffr($n - 1) + ffs($n - 1) }
sub ffs ($n) { %s{$n} //= (grep none(map &ffr, 1..$n), max(%s.values)+1..*)[0] }
my @ffr = map &ffr, 1..*;
my @ffs = map &ffs, 1..*;
say @ffr[^10];
say "Rawks!" if 1...1000 eqv sort |@ffr[^40], |@ffs[^960]; |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #Perl | Perl | use 5.10.0;
use strict;
use warnings;
sub horner(\@$){
my ($coef, $x) = @_;
my $result = 0;
$result = $result * $x + $_ for reverse @$coef;
return $result;
}
my @coeff = (-19.0, 7, -4, 6);
my $x = 3;
say horner @coeff, $x; |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #Phix | Phix | with javascript_semantics
function horner(atom x, sequence coeff)
atom res = 0
for i=length(coeff) to 1 by -1 do
res = res*x + coeff[i]
end for
return res
end function
?horner(3,{-19, 7, -4, 6})
|
http://rosettacode.org/wiki/Hilbert_curve | Hilbert curve |
Task
Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
| #Rust | Rust | // [dependencies]
// svg = "0.8.0"
use svg::node::element::path::Data;
use svg::node::element::Path;
struct HilbertCurve {
current_x: f64,
current_y: f64,
current_angle: i32,
line_length: f64,
}
impl HilbertCurve {
fn new(x: f64, y: f64, length: f64, angle: i32) -> HilbertCurve {
Hilbe... |
http://rosettacode.org/wiki/Hilbert_curve | Hilbert curve |
Task
Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
| #Scala | Scala | @js.annotation.JSExportTopLevel("ScalaFiddle")
object ScalaFiddle {
// $FiddleStart
import scala.util.Random
case class Point(x: Int, y: Int)
def xy2d(order: Int, d: Int): Point = {
def rot(order: Int, p: Point, rx: Int, ry: Int): Point = {
val np = if (rx == 1) Point(order - 1 - p.x, order - 1 - ... |
http://rosettacode.org/wiki/Holidays_related_to_Easter | Holidays related to Easter | Task
Calculate the dates of:
Easter
Ascension Thursday
Pentecost
Trinity Sunday
Corpus Christi feast (for Catholic)
All Saints' Sunday (for Orthodox)
As an example, calculate for the first year of each century from;
years 400 to 2100 CE and for
years 2010 to 2020 CE.
Note
... | #Perl | Perl | #!/usr/bin/perl
use strict; use warnings;
use Date::Calc qw(:all);
my @abbr = qw( Not Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my %c_hols = (
Easter=> 0,
Ascension=> 39,
Pentecost=> 49,
Trinity=> 56,
Corpus=> 60
);
sub easter {
my $year=shift;
my $ay=$year % 19;
my $by=int($yea... |
http://rosettacode.org/wiki/Horizontal_sundial_calculations | Horizontal sundial calculations | Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit... | #PicoLisp | PicoLisp | (load "@lib/math.l")
(de prompt (Str . Arg)
(prin Str " => ")
(set (car Arg) (in NIL (read))) )
(use (Lat Lng Ref)
(prompt "Enter latitude " Lat)
(prompt "Enter longitude " Lng)
(prompt "Enter legal meridian" Ref)
(prinl)
(let Slat (sin (*/ Lat pi 180.0))
(prinl " sine of lati... |
http://rosettacode.org/wiki/Horizontal_sundial_calculations | Horizontal sundial calculations | Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit... | #PowerShell | PowerShell |
function Get-Sundial
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true)]
[ValidateRange(-90,90)]
[double]
$Latitude,
[Parameter(Mandatory=$true)]
[ValidateRange(-180,180)]
[double]
$Longitude,
... |
http://rosettacode.org/wiki/Huffman_coding | Huffman coding | Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols.
For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi... | #Raku | Raku | sub huffman (%frequencies) {
my @queue = %frequencies.map({ [.value, .key] }).sort;
while @queue > 1 {
given @queue.splice(0, 2) -> ([$freq1, $node1], [$freq2, $node2]) {
@queue = (|@queue, [$freq1 + $freq2, [$node1, $node2]]).sort;
}
}
hash gather walk @queue[0][1], '';
}
... |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Tcl | Tcl | proc I {rank {zero 0.0} {one 1.0}} {
set m [lrepeat $rank [lrepeat $rank $zero]]
for {set i 0} {$i < $rank} {incr i} {
lset m $i $i $one
}
return $m
} |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Tcl | Tcl | puts "Please enter two numbers:"
gets stdin x
gets stdin y
if { $x > $y } { puts "$x is greater than $y" }
if { $x < $y } { puts "$x is less than $y" }
if { $x == $y } { puts "$x equals $y" } |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #TI-83_BASIC | TI-83 BASIC | Prompt A,B
If A<B: Disp "A SMALLER B"
If A>B: Disp "A GREATER B"
If A=B: Disp "A EQUAL B" |
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.
| #Lasso | Lasso | // using include_url wrapper:
include_url('http://rosettacode.org/index.html')
// one line curl
curl('http://rosettacode.org/index')->result->asString
// using curl for more complex operations and feedback
local(x = curl('http://rosettacode.org/index'))
local(y = #x->result)
#y->asString |
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.
| #LFE | LFE | (: inets start)
(case (: httpc request '"http://lfe.github.io")
((tuple 'ok result)
(: io format '"Result: ~p" (list result)))
((tuple 'error reason)
(: io format '"Error: ~p~n" (list reason))))
|
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence | Hofstadter-Conway $10,000 sequence | The definition of the sequence is colloquially described as:
Starting with the list [1,1],
Take the last number in the list so far: 1, I'll call it x.
Count forward x places from the beginning of the list to find the first number to add (1)
Count backward x places from the end of the list to find the secon... | #Perl | Perl | #!/usr/bin/perl
use warnings ;
use strict ;
my $limit = 2 ** 20 ;
my @numbers = ( 0 , 1 , 1 ) ;
my $mallows ;
my $max_i ;
foreach my $i ( 3..$limit ) {
push ( @numbers , $numbers[ $numbers[ $i - 1 ]] + $numbers[ $i - $numbers[ $i - 1 ] ] ) ;
}
for ( my $rangelimit = 1 ; $rangelimit < 20 ; $rangelimit++ ) {
my ... |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Maple | Maple |
error "Goodbye World"
|
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Write[Streams["stderr"], "Goodbye, World!"] |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #MATLAB_.2F_Octave | MATLAB / Octave | fprintf(2,'Goodbye, World!') |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Mercury | Mercury |
:- module hello_error.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
main(!IO) :-
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, "Goodbye, World!\n", !IO).
|
http://rosettacode.org/wiki/Hofstadter_Q_sequence | Hofstadter Q sequence | Hofstadter Q sequence
Q
(
1
)
=
Q
(
2
)
=
1
,
Q
(
n
)
=
Q
(
n
−
Q
(
n
−
1
)
)
+
Q
(
n
−
Q
(
n
−
2
)
)
,
n
>
2.
{\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}}
It is defined like the Fibonacc... | #Haskell | Haskell | qSequence = tail qq where
qq = 0 : 1 : 1 : map g [3..]
g n = qq !! (n - qq !! (n-1)) + qq !! (n - qq !! (n-2))
-- Output:
*Main> (take 10 qSequence, qSequence !! (1000-1))
([1,1,2,3,3,4,5,5,6,6],502)
(0.00 secs, 525044 bytes) |
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
| #Agda | Agda | module helloworld where
open import Agda.Builtin.IO using (IO)
open import Agda.Builtin.Unit renaming (⊤ to Unit)
open import Agda.Builtin.String using (String)
postulate putStrLn : String -> IO Unit
{-# FOREIGN GHC import qualified Data.Text as T #-}
{-# COMPILE GHC putStrLn = putStrLn . T.unpack #-}
main : IO U... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.