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/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
#ALGOL_60
ALGOL 60
'BEGIN' OUTSTRING(1,'('Hello world!')'); SYSACT(1,14,1) 'END'
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...
#ooRexx
ooRexx
/*REXX pgm generates primitive Heronian triangles by side length & area.*/ Call time 'R' Numeric Digits 12 Parse Arg mxs area list If mxs ='' Then mxs =200 If area='' Then area=210 If list='' Then list=10 tx='primitive Heronian triangles' Call heronian mxs /* invoke sub with max SIDES. */...
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
#D
D
int hof(int a, int b, int delegate(int, int) f) { return f(a, b); }   void main() { import std.stdio; writeln("Add: ", hof(2, 3, (a, b) => a + b)); writeln("Multiply: ", hof(2, 3, (a, b) => a * b)); }
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...
#PHP
PHP
<?php // AF_INET6 for IPv6 // IP $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!'); // '127.0.0.1' to limit only to localhost // Port socket_bind($socket, 0, 8080); socket_listen($socket);   $msg = '<html><h...
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...
#PicoLisp
PicoLisp
(html 0 "Bye" NIL NIL "Goodbye, World!" )
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...
#Tcl
Tcl
package require Tcl 8.5 package require struct::set   # Core sequence generator engine; stores in $R and $S globals set R {R:-> 1} set S {S:-> 2} proc buildSeq {n} { global R S set ctr [expr {max([lindex $R end],[lindex $S end])}] while {[llength $R] <= $n || [llength $S] <= $n} { set idx [expr {min([lleng...
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...
#Python
Python
>>> def horner(coeffs, x): acc = 0 for c in reversed(coeffs): acc = acc * x + c return acc   >>> horner( (-19, 7, -4, 6), 3) 128
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...
#R
R
horner <- function(a, x) { y <- 0 for(c in rev(a)) { y <- y * x + c } y }   cat(horner(c(-19, 7, -4, 6), 3), "\n")
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.
#XPL0
XPL0
def Order=5, Size=15; \length of line segment int Dir, X, Y;   proc GoFwd; [case Dir&3 of 0: X:= X+Size; 1: Y:= Y+Size; 2: X:= X-Size; 3: Y:= Y-Size other []; Line(X, Y, \white\7); ];   proc Hilbert(Lev, Ang); int Lev, Ang; [if Lev then [Dir:= Dir+Ang; Hilbert(Lev-1, -Ang); GoFwd; Dir:= Dir-Ang...
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.
#Yabasic
Yabasic
width = 64   sub hilbert(x, y, lg, i1, i2) if lg = 1 then line to (width-x) * 10, (width-y) * 10 return end if lg = lg / 2 hilbert(x+i1*lg, y+i1*lg, lg, i1, 1-i2) hilbert(x+i2*lg, y+(1-i2)*lg, lg, i1, i2) hilbert(x+(1-i1)*lg, y+(1-i1)*lg, lg, i1, i2) hilbert(x+(1-i2)*lg, y+i2...
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 ...
#PureBasic
PureBasic
DataSection C_DAYS: Data.i 0,39,49,56,60 END_C_DAYS: DAYS_MT: Data.i 0,31,28,31,30,31,30,31,31,30,31,30,31 END_DAYS_MT: EndDataSection   Dim m.s{3}(12)  : PokeS(@m(),"___JanFebMarAprMayJunJulAugSepOctNovDec") Dim dom.i(12)  : CopyMemory(?DAYS_MT,@dom(),?END_DAYS_MT-?DAYS_MT) Structure tDate : yyyy.i : mm.i...
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...
#Ring
Ring
  # Project : Horizontal sundial calculations   load "stdlib.ring" pi = 22/7 decimals(3)   latitude = -4.95 longitude = -150.5 meridian = -150.0   see "enter latitude (degrees): " + latitude + nl see "enter longitude (degrees): " + longitude + nl see "enter legal meridian (degrees): " + meridian + nl   see "time " + ...
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...
#Ruby
Ruby
include Math DtoR = PI/180   print 'Enter latitude: ' lat = Float( gets ) print 'Enter longitude: ' lng = Float( gets ) print 'Enter legal meridian: ' ref = Float( gets ) puts   slat = sin( lat * DtoR )   puts " sine of latitude:  %.3f"% slat puts " diff longitude:  %.3f"% (lng-ref) puts puts 'Hour, sun hour an...
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...
#Scala
Scala
object Huffman { import scala.collection.mutable.{Map, PriorityQueue}   sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree   def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) ...
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 ⋮ ⋮ ⋮ ⋱ ...
#Visual_Basic
Visual Basic
Option Explicit '------------ Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte() Dim i As Long Dim b() As Byte   Size = Size - 1 ReDim b(0 To Size, 0 To Size) 'at this point, the matrix is allocated and 'all elements are initialized to 0 (zero) For i = 0 To Size b(i, i) = 1 'set diagonal ...
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 |...
#VBA
VBA
Public Sub integer_comparison() first_integer = CInt(InputBox("Give me an integer.")) second_integer = CInt(InputBox("Give me another integer.")) Debug.Print IIf(first_integer < second_integer, "first integer is smaller than second integer", "first integer is not smaller than second integer") Debug.Prin...
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 |...
#VBScript
VBScript
  option explicit   function eef( b, r1, r2 ) if b then eef = r1 else eef = r2 end if end function   dim a, b wscript.stdout.write "First integer: " a = cint(wscript.stdin.readline) 'force to integer wscript.stdout.write "Second integer: " b = cint(wscript.stdin.readline) 'force to integer wscript.stdout.write...
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  Print[Import["http://www.google.com/webhp?complete=1&hl=en", "Source"]]  
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...
#Racket
Racket
#lang racket/base   (define-syntax-rule (define/memoize1 (proc x) body ...) (define proc (let ([cache (make-hash)] [direct (lambda (x) body ...)]) (lambda (x) (hash-ref! cache x (lambda () (direct x)))))))   (define/memoize1 (conway n) (if (< n 3) 1 (+ (conway (conway (sub1 ...
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...
#Raku
Raku
my $n = 3; my @a = (0,1,1, -> $p { @a[$p] + @a[$n++ - $p] } ... *); @a[2**20]; # pre-calculate sequence   my $last55; for 1..19 -> $power { my @range := 2**$power .. 2**($power+1)-1; my @ratios = (@a[@range] Z/ @range) Z=> @range; my $max = @ratios.max; ($last55 = .value if .key >= .55 for @ratios) if $...
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 ...
#ooRexx
ooRexx
.error~lineout("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 ...
#Oz
Oz
functor import Application System define {System.showError "Goodbye, World!"} {Application.exit 0} end
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 ...
#PARI.2FGP
PARI/GP
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 ...
#Pascal
Pascal
program byeworld;   begin writeln(StdErr, 'Goodbye, World!'); end.
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...
#jq
jq
  # For n>=2, Q(n) = Q(n - Q(n-1)) + Q(n - Q(n-2)) def Q: def Q(n): n as $n | (if . == null then [1,1,1] else . end) as $q | if $q[$n] != null then $q else $q | Q($n-1) as $q1 | $q1 | Q($n-2) as $q2 | $q2 | Q($n - $q2[$n - 1]) as $q3 # Q(n - Q(n-1)) | $q3 | Q($n - ...
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
#ALGOL_68
ALGOL 68
main: ( printf($"Hello world!"l$) )
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...
#PARI.2FGP
PARI/GP
Heron(v)=my([a,b,c]=v); (a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c) \\ returns 16 times the squared area is(a,b,c)=(a+b+c)%2==0 && gcd(a,gcd(b,c))==1 && issquare(Heron([a,b,c])) v=List(); for(a=1,200,for(b=a+1,200,for(c=b+1,200, if(is(a,b,c),listput(v, [a,b,c]))))); v=Vec(v); #v vecsort(v, (a,b)->Heron(a)-Heron(b))[1..10] vecsort...
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
#Delphi
Delphi
type TFnType = function(x : Float) : Float;   function First(f : TFnType) : Float; begin Result := f(1) + 2; end;   function Second(f : Float) : Float; begin Result := f/2; end;   PrintLn(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...
#Pike
Pike
  void handle_request(Protocols.HTTP.Server.Request request) { request->response_and_finish( ([ "data":"Goodbye, World!", "type":"text/html" ]) ); }   int main() { Protocols.HTTP.Server.Port(handle_request, 8080); return -1; // -1 is a special case that retirns control t...
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...
#Pony
Pony
  use "net"   actor Main new create(env: Env) => try TCPListener(env.root as AmbientAuth, Listener, "127.0.0.1", "8080") else env.err.print("unable to use the network") end   // Boilerplate code, create a TCP listener on a socket class Listener is TCPListenNotify   new is...
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...
#uBasic.2F4tH
uBasic/4tH
Proc _SetBitR(1) ' Set the first R value Proc _SetBitS(2) ' Set the first S value   Print "Creating bitmap, wait.." ' Create the bitmap Proc _MakeBitMap Print   Print "R(1 .. 10):"; ' Print first 10 R-values   For x = 1 To 10 Print " ";FUNC(_Rx(x));...
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...
#VBA
VBA
Private Function ffr(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 'return R(n) For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 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...
#Racket
Racket
  #lang racket (define (horner x l) (foldr (lambda (a b) (+ a (* b x))) 0 l))   (horner 3 '(-19 7 -4 6))    
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...
#Raku
Raku
sub horner ( @coeffs, $x ) { @coeffs.reverse.reduce: { $^a * $x + $^b }; }   say 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.
#zkl
zkl
hilbert(6) : turtle(_);   fcn hilbert(n){ // Lindenmayer system --> Data of As & Bs var [const] A="-BF+AFA+FB-", B="+AF-BFB-FA+"; buf1,buf2 := Data(Void,"A").howza(3), Data().howza(3); // characters do(n){ buf1.pump(buf2.clear(),fcn(c){ if(c=="A") A else if(c=="B") B else c }); t:=buf1; buf1=buf2;...
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 ...
#Python
Python
from dateutil.easter import * import datetime, calendar   class Holiday(object): def __init__(self, date, offset=0): self.holiday = date + datetime.timedelta(days=offset)   def __str__(self): dayofweek = calendar.day_name[self.holiday.weekday()][0:3] month = calendar.month_name[self.holi...
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...
#Run_BASIC
Run BASIC
global pi pi = 22 / 7   print "Enter latitude (degrees)  : "; :input latitude ' -4.95 print "Enter longitude (degrees)  : "; :input longitude ' -150.5 print "Enter legal meridian (degrees): "; :input meridian ' -150.0   print print "Time Sun hour angle Dial hour line angle"   for hour ...
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...
#Rust
Rust
  use std::io; struct SundialCalculation { hour_angle: f64, hour_line_angle: f64, }   fn get_input(prompt: &str) -> Result<f64, Box<dyn std::error::Error>> { println!("{}", prompt); let mut input = String::new(); let stdin = io::stdin(); stdin.read_line(&mut input)?; Ok(input.trim().parse::<...
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...
#Scheme
Scheme
(define (char-freq port table) (if (eof-object? (peek-char port)) table (char-freq port (add-char (read-char port) table))))   (define (add-char char table) (cond ((null? table) (list (list char 1))) ((eq? (caar table) char) (cons (list char (+ (cadar table) 1)) (cdr table))) (#t (cons (car table)...
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 ⋮ ⋮ ⋮ ⋱ ...
#Wortel
Wortel
@let { im ^(%^\@table ^(@+ =) @to)    !im 4 }
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 ⋮ ⋮ ⋮ ⋱ ...
#Wren
Wren
import "/matrix" for Matrix import "/fmt" for Fmt   var numRows = 10 // say Fmt.mprint(Matrix.identity(numRows), 2, 0)
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 |...
#Visual_Basic_.NET
Visual Basic .NET
Sub Main()   Dim a = CInt(Console.ReadLine) Dim b = CInt(Console.ReadLine)   'Using if statements If a < b Then Console.WriteLine("a is less than b") If a = b Then Console.WriteLine("a equals b") If a > b Then Console.WriteLine("a is greater than b")   'Using Case Select Case a C...
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.
#MATLAB_.2F_Octave
MATLAB / Octave
  >> random = urlread('http://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new')   random =   61  
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.
#MIRC_Scripting_Language
MIRC Scripting Language
import http import url   url = new(URL, "http://rosettacode.org/wiki/Rosetta_Code") client = new(HTTPClient, url.getHost()) client.connect()   response = client.get(url.getFile()) println response.get("body")
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...
#REXX
REXX
/*REXX program solves the Hofstadter─Conway sequence $10,000 prize (puzzle). */ @pref= 'Maximum of a(n) ÷ n between ' /*a prologue for the text of message. */ H.=.; H.1=1; H.2=1;  !.=0; @.=0 /*initialize some REXX variables. */ win=0 do k=0 to 20; p.k=2**k; maxp=...
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 ...
#Perl
Perl
warn "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 ...
#Phix
Phix
puts(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 ...
#PHP
PHP
fprintf(STDERR, "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 ...
#Picat
Picat
println(stderr,"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...
#Julia
Julia
function hofstQseq(n, typerst::Type=Int) nmax = maximum(n) r = Vector{typerst}(nmax) r[1] = 1 if nmax ≥ 2 r[2] = 1 end for i in 3:nmax r[i] = r[i - r[i - 1]] + r[i - r[i - 2]] end return r[n] end   println("First ten elements of sequence: ", join(hofstQseq(1:10), ", ")) println("1000...
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...
#Kotlin
Kotlin
// version 1.1.4   fun main(args: Array<String>) { val q = IntArray(100_001) q[1] = 1 q[2] = 1 for (n in 3..100_000) q[n] = q[n - q[n - 1]] + q[n - q[n - 2]] print("The first 10 terms are : ") for (i in 1..10) print("${q[i]} ") println("\n\nThe 1000th term is : ${q[1000]}") val flips = ...
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
#ALGOL_W
ALGOL W
begin write( "Hello world!" ) end.
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...
#Pascal
Pascal
program heronianTriangles ( input, output ); type (* record to hold details of a Heronian triangle *) Heronian = record a, b, c, area, perimeter : integer end; refHeronian = ^Heronian;   var   ht : array [ 1 .. 1000 ] of refHeronian; htCount, htPos : integer; a, b, c, i : inte...
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
#DWScript
DWScript
type TFnType = function(x : Float) : Float;   function First(f : TFnType) : Float; begin Result := f(1) + 2; end;   function Second(f : Float) : Float; begin Result := f/2; end;   PrintLn(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...
#Prolog
Prolog
% The following modules are used in the main module to start a server. :- use_module(library(http/thread_httpd)). :- use_module(library(http/http_dispatch)).   % The following module is used in every module that describes a page. :- use_module(library(http/html_write)).   % Main entry point: starts the server on port 8...
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...
#PureBasic
PureBasic
If InitNetwork() = 0 MessageRequester("Error", "Can't initialize the network !") End EndIf   Port = 8080   If CreateNetworkServer(0, Port) Repeat Delay(1) SEvent = NetworkServerEvent() If SEvent ClientID = EventClient() Select SEvent Case #PB_NetworkEvent_Data SendNetwork...
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...
#VBScript
VBScript
  'Initialize the r and the s arrays. Set r = CreateObject("System.Collections.ArrayList") Set s = CreateObject("System.Collections.ArrayList")   'Set initial values of r. r.Add ""  : r.Add 1   'Set initial values of s. s.Add "" : s.Add 2   'Populate the r and the s arrays. For i = 2 To 1000 ffr(i) ffs(i) Next   'r f...
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...
#Wren
Wren
var r = [0, 1] var s = [0, 2]   var ffr = Fn.new { |n| while (r.count <= n) { var nrk = r.count - 1 // last n for which r[n] is known var rNxt = r[nrk] + s[nrk] // r[nrk+1] r.add(rNxt) // extend r by one element for (sn in r[nrk]+2...rNxt) { 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...
#Rascal
Rascal
import List;   public int horners_rule(list[int] coefficients, int x){ acc = 0; for( i <- reverse(coefficients)){ acc = acc * x + i;} return acc; }
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...
#REBOL
REBOL
rebol []   horner: func [coeffs x] [ result: 0 foreach i reverse coeffs [ result: (result * x) + i ] return result ]   print horner [-19 7 -4 6] 3
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 ...
#R
R
  library(tidyverse) library(lubridate) # Make a pretty date function: pretty_date = stamp_date("Thu, Jun 1, 2000")   # Gregorian calendar: tibble(year = c(seq(400, 2100, 100), 2010:2020)) %>% arrange(year) %>% mutate(a = year %% 19, b = year %% 4, c = year %% 7, k = year %/% 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...
#Sather
Sather
class MAIN is   getvalue(s:STR):FLT is #OUT + s + ": "; return #FLT(#IN.get_line.str); end;   dr(a:FLT):FLT is return a * FLT::pi / 180.0; end;   rd(a:FLT):FLT is return a * 180.0 / FLT::pi; end;   main is lat ::= getvalue("Enter latitude"); lng ::= getvalue("Enter longitude"); ...
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...
#Scala
Scala
import java.util.Scanner   import scala.math.{atan2, cos, sin, toDegrees, toRadians}   object Sundial extends App { var lat, slat,lng, ref = .0 val sc = new Scanner(System.in) print("Enter latitude: ") lat = sc.nextDouble print("Enter longitude: ") lng = sc.nextDouble print("Enter legal meridian: ") ref...
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...
#SETL
SETL
var forest := {}, encTab := {};   plaintext := 'this is an example for huffman encoding';   ft := {}; (for c in plaintext) ft(c) +:= 1; end;   forest := {[f, c]: [c, f] in ft}; (while 1 < #forest) [f1, n1] := getLFN(); [f2, n2] := getLFN(); forest with:= [f1+f2, [n1,n2]]; end; addToTable('', arb range forest); ...
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 ⋮ ⋮ ⋮ ⋱ ...
#XPL0
XPL0
include c:\cxpl\codes; def IntSize = 4; \number of bytes in an integer int Matrix, Size, I, J;   [Text(0, "Size: "); Size:= IntIn(0); Matrix:= Reserve(Size*IntSize); \reserve memory for 2D integer array for I:= 0 to Size-1 do Matrix(I):= Reserve(Size*IntSize); for J:= 0 to Size-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 ⋮ ⋮ ⋮ ⋱ ...
#zkl
zkl
fcn idMatrix(n){ m:=(0).pump(n,List.createLong(n).write,0)*n; m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0)); m } idMatrix(5).println(); idMatrix(5).pump(Console.println);
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 |...
#Wart
Wart
a <- (read) b <- (read) prn (if (a < b)  : "a is less than b" (a > b)  : "a is greater than b"  :else  : "a equals 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 |...
#Wren
Wren
import "io" for Stdin, Stdout   System.print("Enter anything other than a number to quit at any time.\n") while (true) { System.write(" First number  : ") Stdout.flush() var a = Num.fromString(Stdin.readLine()) if (!a) break System.write(" Second number : ") Stdout.flush() var b = Num.from...
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.
#Nanoquery
Nanoquery
import http import url   url = new(URL, "http://rosettacode.org/wiki/Rosetta_Code") client = new(HTTPClient, url.getHost()) client.connect()   response = client.get(url.getFile()) println response.get("body")
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.
#Nemerle
Nemerle
using System; using System.Console; using System.Net; using System.IO;   module HTTP { Main() : void { def wc = WebClient(); def myStream = wc.OpenRead("http://rosettacode.org"); def sr = StreamReader(myStream);   WriteLine(sr.ReadToEnd()); myStream.Close() } }
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...
#Ring
Ring
  decimals(9) size = 15 a = list(pow(2,size)) a[1]=1 a[2]=1 power=2 p2=pow(2,power) peak=0.5 peakpos=0 for n=3 to pow(2,size) a[n]=a[a[n-1]]+a[n-a[n-1]] r=a[n]/n if r>=0.55 mallows=n ok if r>peak peak=r peakpos=n ok if n=p2 see "maximum between 2^" + (power - 1) + " and 2^" + power + " is " ...
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...
#Ruby
Ruby
class HofstadterConway10000 def initialize @sequence = [nil, 1, 1] end   def [](n) raise ArgumentError, "n must be >= 1" if n < 1 a = @sequence a.length.upto(n) {|i| a[i] = a[a[i-1]] + a[i-a[i-1]] } a[n] end end   hc = HofstadterConway10000.new   mallows = nil (1...20).each do |i| j = 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 ...
#PicoLisp
PicoLisp
(out 2 (prinl "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 ...
#Pike
Pike
werror("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 ...
#PL.2FI
PL/I
display ('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 ...
#PostScript
PostScript
(%stderr) (w) file dup (Goodbye, World! ) writestring closefile
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...
#MAD
MAD
NORMAL MODE IS INTEGER VECTOR VALUES FMT = $2HQ(,I4,3H) =,I4*$   DIMENSION Q(1000) Q(1) = 1 Q(2) = 1 THROUGH FILL, FOR N=3, 1, N.G.1000 FILL Q(N) = Q(N-Q(N-1)) + Q(N-Q(N-2))   THROUGH SHOW, FOR N=1, 1, N.G.10 SHOW PRINT FO...
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...
#Maple
Maple
Q := proc( n ) option remember, system; if n = 1 or n = 2 then 1 else thisproc( n - thisproc( n - 1 ) ) + thisproc( n - thisproc( n - 2 ) ) end if end proc:
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
#ALGOL-M
ALGOL-M
BEGIN WRITE( "Hello world!" ); END
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...
#Perl
Perl
use strict; use warnings; use List::Util qw(max);   sub gcd { $_[1] == 0 ? $_[0] : gcd($_[1], $_[0] % $_[1]) }   sub hero { my ($a, $b, $c) = @_[0,1,2]; my $s = ($a + $b + $c) / 2; sqrt $s*($s - $a)*($s - $b)*($s - $c); }   sub heronian_area { my $hero = hero my ($a, $b, $c) = @_[0,1,2]; sprintf("%....
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
#Dyalect
Dyalect
func call(f, a, b) { f(a, b) }   let a = 6 let b = 2   print("f=add, f(\(a), \(b)) = \(call((x, y) => x + y, a, b))") print("f=mul, f(\(a), \(b)) = \(call((x, y) => x * y, a, b))") print("f=div, f(\(a), \(b)) = \(call((x, y) => x / y, a, b))")
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...
#Python
Python
from wsgiref.simple_server import make_server   def app(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) yield b"<h1>Goodbye, World!</h1>"   server = make_server('127.0.0.1', 8080, app) server.serve_forever()
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...
#R
R
  library(httpuv)   runServer("0.0.0.0", 5000, list( call = function(req) { list(status = 200L, headers = list('Content-Type' = 'text/html'), body = "Hello world!") } ) )      
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...
#zkl
zkl
fcn genRS(reset=False){ //-->(n,R,S) var n=0, Rs=L(0,1), S=2; if(True==reset){ n=0; Rs=L(0,1); S=2; return(); }   if (n==0) return(n=1,1,2); R:=Rs[-1] + S; Rs.append(R); foreach s in ([S+1..]){ if(not Rs.holds(s)) { S=s; break; } // trimming Rs doesn't save space } return(n+=1,R,S); } fcn ffrs(n) { g...
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...
#REXX
REXX
/*REXX program demonstrates using Horner's rule for polynomial evaluation. */ numeric digits 30 /*use extra numeric precision. */ parse arg x poly /*get value of X and the coefficients. */ $= ...
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...
#Ring
Ring
  coefficients = [-19, 7, -4, 6] see "x = 3" + nl + "degree = 3" + nl + "equation = 6*x^3-4*x^2+7*x-19" + nl + "result = " + horner(coefficients, 3) + nl   func horner coeffs, x w = 0 for n = len(coeffs) to 1 step -1 w = w * x + coeffs[n] next return w  
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 ...
#Racket
Racket
my @abbr = < Nil Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec >;   my @holidays = Easter => 0, Ascension => 39, Pentecost => 49, Trinity => 56, Corpus => 60;   sub easter($year) { my \ay = $year % 19; my \by = $year div 100; my \cy = $year % 100; my \dy = by div 4; my ...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const float: radianToDegrees is 57.295779513082320876798154814114; const float: degreesToRadian is 0.017453292519943295769236907684883;   const proc: main is func local var float: lat is 0.0; var float: slat is 0.0; var float: lng is...
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...
#Sidef
Sidef
var latitude = read('Enter latitude => ', Number) var longitude = read('Enter longitude => ', Number) var meridian = read('Enter legal meridian => ', Number)   var lat_sin = latitude.deg2rad.sin var offset = (meridian - longitude)   say('Sine of latitude: ', "%.4f" % lat_sin) say('Longitude offset: ', offs...
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...
#Sidef
Sidef
func walk(n, s, h) { if (n.contains(:a)) { h{n{:a}} = s say "#{n{:a}}: #{s}" return nil } walk(n{:0}, s+'0', h) walk(n{:1}, s+'1', h) }   func make_tree(text) { var letters = Hash() text.each { |c| letters{c} := 0 ++ } var nodes = letters.keys.map { |l| Hash(a...
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 ⋮ ⋮ ⋮ ⋱ ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 INPUT "Matrix size: ";size 20 GO SUB 200: REM Identity matrix 30 FOR r=1 TO size 40 FOR c=1 TO size 50 LET s$=CHR$ 13 60 IF c<size THEN LET s$=" " 70 PRINT i(r,c);s$; 80 NEXT c 90 NEXT r 100 STOP 200 REM Identity matrix size 220 DIM i(size,size) 230 FOR i=1 TO size 240 LET i(i,i)=1 250 NEXT i 260 RETURN
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 |...
#XLISP
XLISP
(DEFUN COMPARE-INTEGERS () (DISPLAY "Enter two integers separated by a space.") (NEWLINE) (DISPLAY "> ") (DEFINE A (READ)) (DEFINE B (READ)) (COND ((> A B) (DISPLAY "The first number is larger.")) ((= A B) (DISPLAY "They are equal.")) ((< A B) (DISPLAY "The first number i...
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 |...
#XPL0
XPL0
code IntIn=10, Text=12; int A, B; [A:= IntIn(0); B:= IntIn(0); if A<B then Text(0, "A<B"); if A=B then Text(0, "A=B"); if A>B then Text(0, "A>B"); CrLf(0); ]
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import java.util.Scanner import java.net.URL   do rosettaUrl = "http://www.rosettacode.org" sc = Scanner(URL(rosettaUrl).openStream) loop while sc.hasNext say sc.nextLine end catch ex = Exception ex.printStackTrace end   return
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...
#Rust
Rust
  struct HofstadterConway { current: usize, sequence: Vec<usize>, }   impl HofstadterConway { /// Define a constructor for the struct. fn new() -> HofstadterConway { HofstadterConway { current: 0, sequence: vec![1, 1], } } }   impl Default for HofstadterConway...
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...
#Scala
Scala
object HofstadterConway { def pow2(n: Int): Int = (Iterator.fill(n)(2)).product   def makeHCSequence(max: Int): Seq[Int] = (0 to max - 1).foldLeft (Vector[Int]()) { (v, idx) => if (idx <= 1) v :+ 1 else v :+ (v(v(idx - 1) - 1) + v(idx - v(idx - 1))) }   val max = pow2(20)   val maxSeq = makeHCSe...
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 ...
#PowerBASIC
PowerBASIC
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 ...
#PowerShell
PowerShell
Write-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 ...
#PureBasic
PureBasic
ConsoleError("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 ...
#Python
Python
import sys   print >> sys.stderr, "Goodbye, World!"