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/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... | #jq | jq | # input should be an array of the lengths of the sides
def hero:
(add/2) as $s
| ($s*($s - .[0])*($s - .[1])*($s - .[2])) as $a2
| if $a2 > 0 then ($a2 | sqrt) else 0 end;
def is_heronian:
hero as $h
| $h > 0 and ($h|floor) == $h;
def gcd3(x; y; z):
# subfunction expects [a,b] as input
def rgcd:
i... |
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... | #Julia | Julia |
type IntegerTriangle{T<:Integer}
a::T
b::T
c::T
p::T
σ::T
end
function IntegerTriangle{T<:Integer}(a::T, b::T, c::T)
p = a + b + c
s = div(p, 2)
σ = isqrt(s*(s-a)*(s-b)*(s-c))
(x, y, z) = sort([a, b, c])
IntegerTriangle(x, y, z, p, σ)
end
function isprimheronian{T<:Integer}... |
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
| #CLU | CLU | % Functions can be passed to other functions using the 'proctype'
% type generator. The same works for iterators, using 'itertype'
% Here are two functions
square = proc (n: int) returns (int) return (n*n) end square
cube = proc (n: int) returns (int) return (n*n*n) end cube
% Here is a function that takes another ... |
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... | #Objeck | Objeck |
use Net;
use Concurrency;
bundle Default {
class GoodByeWorld {
function : Main(args : String[]) ~ Nil {
server := TCPSocketServer->New(8080);
if(server->Listen(5)) {
while(true) {
client := server->Accept();
client->WriteString("<html>\n<body>\nGoodbye, world!\n</body>... |
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... | #OCaml | OCaml | let try_finalise f x finally y =
let res = try f x with e -> finally y; raise e in
finally y;
res
let rec restart_on_EINTR f x =
try f x with Unix.Unix_error (Unix.EINTR, _, _) -> restart_on_EINTR f x
let double_fork_treatment server service (client_descr, _ as client) =
let treat () =
match Unix.fork... |
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 ... | #XSLT | XSLT | <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
<xsl:template match="/">
<![CDATA[
This text is in a CDATA section. In here, it's okay to include <, >, &, ", and '
without any special treatment.
The section is termi... |
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 ... | #Yabasic | Yabasic |
text1$ = "Esta es la primera linea.
Esta es la segunda linea.
Esta \"linea\" contiene comillas.\n"
text2$ = "Blast it James! I'm a magician,
not a doctor!
--- L. McCoy\n"
print text1$
print text2$
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 ... | #zkl | zkl | x:=
#<<<
"#<<< starts a block of lines that are concatenated verbatim
and fed into the parser as one line. #<<< ends the block.
Both #<<< tokens must start the line that is otherwise ignored
Note that is isn't a string, but arbitrary source " + 1 + 23;
#<<<
x.println(); |
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... | #REXX | REXX | /*REXX program calculates and verifies the Hofstadter Figure─Figure sequences. */
parse arg x top bot . /*obtain optional arguments from the CL*/
if x=='' | x=="," then x= 10 /*Not specified? Then use the default.*/
if top=='' | top=="," then top=1000 ... |
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... | #PHP | PHP | <?php
function horner($coeff, $x) {
$result = 0;
foreach (array_reverse($coeff) as $c)
$result = $result * $x + $c;
return $result;
}
$coeff = array(-19.0, 7, -4, 6);
$x = 3;
echo horner($coeff, $x), "\n";
?> |
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... | #Picat | Picat | horner([],_X,0).
horner([H|T],X,V) :-
horner(T,X,V1),
V = V1 * X + H. |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
const integer: delta is 8;
const proc: drawDown (inout integer: x, inout integer: y, in integer: n) is forward;
const proc: drawUp (inout integer: x, inout integer: y, in integer: n) is forward;
const proc: drawRight (inout integer: x, inout i... |
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.
| #Sidef | Sidef | require('Image::Magick')
class Turtle(
x = 500,
y = 500,
angle = 0,
scale = 1,
mirror = 1,
xoff = 0,
yoff = 0,
color = 'black',
) {
has im = %O<Image::Magick>.new(size => "#{x}x#{y}")
method init {
angle.deg2rad!
im.ReadImage('canvas:white')... |
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
... | #Phix | Phix | -- demo\rosetta\Easter.exw
function easter(integer year)
-- from https://en.wikipedia.org/wiki/Computus#Anonymous_Gregorian_algorithm
integer a = mod(year,19),
b = floor(year/100),
c = mod(year,100),
d = floor(b/4),
e = mod(b,4),
f = floor((b+8)/25),
... |
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... | #PureBasic | PureBasic | If OpenConsole()
Define.f lat, slat, lng, ref
Define.i h
Print("Enter latitude => "): lat=ValF(Input())
Print("Enter longitude => "): lng=ValF(Input())
Print("Enter legal meridian => "): ref=ValF(Input())
PrintN("")
slat=Sin(lat*2*#PI/360)
PrintN(" sine of latitude: "+StrF(slat,3))
P... |
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... | #Red | Red | Red [file: %huffy.red]
;; message to encode:
msg: "this is an example for huffman encoding"
;;map to collect leave knots per uniq character of message
m: make map! []
knot: make object! [
left: right: none ;; pointer to left/right sibling
code: none ;; first holds char for debugging, later binary co... |
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
⋮
⋮
⋮
⋱
... | #TypeScript | TypeScript |
function identity(n) {
if (n < 1) return "Not defined";
else if (n == 1) return 1;
else {
var idMatrix:number[][];
for (var i: number = 0; i < n; i++) {
for (var j: number = 0; j < n; j++) {
if (i != j) idMatrix[i][j] = 0;
else idMatrix[i][j] = 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 |... | #TI-89_BASIC | TI-89 BASIC | Local a, b, result
Prompt a, b
If a < b Then
"<" → result
ElseIf a = b Then
"=" → result
ElseIf a > b Then
">" → result
Else
"???" → result
EndIf
Disp string(a) & " " & result & " " & string(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.
| #Liberty_BASIC | Liberty BASIC |
result = DownloadToFile( "http://rosettacode.org/wiki/Main_Page", "in.html")
timer 2000, [on]
wait
[on]
timer 0
if result <> 0 then print "Error downloading."
end
Function DownloadToFile( urlfile$, localfile$)
open "URLmon" for dll as #url
calldll #url, "URLDownloadToFileA",_
0 as long,_ '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... | #Phix | Phix | with javascript_semantics
sequence a = {1,1}
function q(integer n)
for l=length(a)+1 to n do
a &= a[a[l-1]]+a[l-a[l-1]]
end for
return a[n]
end function
integer mallows = -1, max_n
for p=0 to 19 do
atom max_an = 0.5
integer l = power(2,p), h=l*2
for n=l to h do
atom an = q(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 ... | #Metafont | Metafont | errmessage "Error";
message "...going on..."; % if the user decides to go on and not to stop
% the program because of the error. |
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 ... | #ML.2FI | ML/I | MCSET S4=1
MCNOTE 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 ... | #Modula-2 | Modula-2 | MODULE HelloErr;
IMPORT StdError;
BEGIN
StdError.WriteString('Goodbye, World!');
StdError.WriteLn
END HelloErr. |
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 ... | #Modula-3 | Modula-3 | MODULE Stderr EXPORTS Main;
IMPORT Wr, Stdio;
BEGIN
Wr.PutText(Stdio.stderr, "Goodbye, World!\n");
END Stderr. |
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... | #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
V := [1, 1, 2, 3, 3, 4, 5, 5, 6, 6]
every i := 1 to *V do
if Q(i) ~= V[i] then stop("Assertion failure for position ",i)
printf("Q(1 to %d) - verified.\n",*V)
q := Q(n := 1000)
v := 502
printf("Q[%d]=%d - %s.\n",n,v,if q = v then "verified" else "failed")
invcount := 0
every i :... |
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
| #Agena | Agena | print( "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... | #Kotlin | Kotlin | import java.util.ArrayList
object Heron {
private val n = 200
fun run() {
val l = ArrayList<IntArray>()
for (c in 1..n)
for (b in 1..c)
for (a in 1..b)
if (gcd(gcd(a, b), c) == 1) {
val p = 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
| #CoffeeScript | CoffeeScript | double = [1,2,3].map (x) -> x*2 |
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... | #Ol | Ol | (import (lib http))
(http:run 8080 (lambda (fd request headers send close)
(send "HTTP/1.0 200 OK\n"
"Connection: close\n"
"Content-Type: text/html; charset=UTF-8\n"
"Server: " (car *version*) "/" (cdr *version*)
"\n\n"
"<h1>Goodbye, World!</h1>"
(ref request... |
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... | #Opa | Opa | server = one_page_server("Hello", -> <>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... | #Ring | Ring |
# Project : Hofstadter Figure-Figure sequences
hofr = list(20)
hofr[1] = 1
hofs = []
add(hofs,2)
for n = 1 to 10
hofr[n+1] = hofr[n] + hofs[n]
if n = 1
add(hofs,4)
else
for p = hofr[n] + 1 to hofr[n+1] - 1
if p != hofs[n]
add(hofs,p)
... |
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... | #Ruby | Ruby | $r = [nil, 1]
$s = [nil, 2]
def buildSeq(n)
current = [ $r[-1], $s[-1] ].max
while $r.length <= n || $s.length <= n
idx = [ $r.length, $s.length ].min - 1
current += 1
if current == $r[idx] + $s[idx]
$r << current
else
$s << current
end
end
end
def ffr(n)
buildSeq(n)
$r[n]
... |
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... | #PicoLisp | PicoLisp | (de horner (Coeffs X)
(let Res 0
(for C (reverse Coeffs)
(setq Res (+ C (* X Res))) ) ) ) |
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... | #PL.2FI | PL/I |
declare (i, n) fixed binary, (x, value) float; /* 11 May 2010 */
get (x);
get (n);
begin;
declare a(0:n) float;
get list (a);
value = a(n);
do i = n to 1 by -1;
value = value*x + a(i-1);
end;
put (value);
end;
|
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.
| #Vala | Vala | struct Point{
int x;
int y;
Point(int px,int py){
x=px;
y=py;
}
}
public class Hilbert : Gtk.DrawingArea {
private int it = 1;
private Point[] points;
private const int WINSIZE = 300;
public Hilbert() {
set_size_request(WINSIZE, WINSIZE);
}
public ... |
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
... | #PicoLisp | PicoLisp | (load "@lib/cal.l") # For 'easter' function
(de dayMon (Dat)
(let D (date Dat)
(list (day Dat *Day) " " (align 2 (caddr D)) " " (get *Mon (cadr D))) ) )
(for Y (append (range 400 2100 100) (range 2010 2020))
(let E (easter Y)
(prinl
(align 4 Y)
" Easter: " (dayMon E)
",... |
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... | #Python | Python | from __future__ import print_function
import math
try: raw_input
except: raw_input = input
lat = float(raw_input("Enter latitude => "))
lng = float(raw_input("Enter longitude => "))
ref = float(raw_input("Enter legal meridian => "))
print()
slat = math.sin(math.radians(lat))
print(" sine of latitude: ... |
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... | #REXX | REXX | /* REXX ---------------------------------------------------------------
* 27.12.2013 Walter Pachl
* 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x)
* 14.03.2018 -"- use format instead of right to diagnose size poblems
* Stem m contains eventually the following node data
* m.i.0id Node id
* m.i.0c character
* ... |
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
⋮
⋮
⋮
⋱
... | #Vala | Vala | int main (string[] args) {
if (args.length < 2) {
print ("Please, input an integer > 0.\n");
return 0;
}
var n = int.parse (args[1]);
if (n <= 0) {
print ("Please, input an integer > 0.\n");
return 0;
}
int[,] array = new int[n, n];
for (var i = 0; i < n; i ++) {
for (var j = 0; j < n; j ++) {
if (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 |... | #Toka | Toka | [ ( a b -- )
2dup < [ ." a is less than b\n" ] ifTrue
2dup > [ ." a is greater than b\n" ] ifTrue
= [ ." a is equal to b\n" ] ifTrue
] is compare-integers
1 1 compare-integers
2 1 compare-integers
1 2 compare-integers |
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 |... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
ASK "Please enter your first integer:": i1=""
ASK "Please enter your second integer:": i2=""
IF (i1!='digits'||i2!='digits') ERROR/STOP "Please insert digits"
IF (i1==i2) PRINT i1," is equal to ",i2
IF (i1<i2) PRINT i1," is less than ",i2
IF (i1>i2) PRINT i1," is greater than ",i2
|
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.
| #Lingo | Lingo | property _netID
property _cbHandler
property _cbTarget
----------------------------------------
-- Simple HTTP GET request
-- @param {string} url
-- @param {symbol} cbHandler
-- @param {object} [cbTarget=_movie]
----------------------------------------
on new (me, url, cbHandler, cbTarget)
if voidP(cbTarget) then 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.
| #LiveCode | LiveCode | put true into libURLFollowHttpRedirects
get URL "http://httpbin.org/html"
put it |
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... | #Picat | Picat | go =>
foreach(N in 0..19)
[Val,Ix] = argmax({a(I)/I : I in 2**N..2**(N+1)}),
printf("Max from 2^%2d..2^%-2d is %0.8f at %d\n",N,N+1,Val,Ix+2**N-1)
end,
println(mallows_number=mallows_number()),
nl.
% The sequence definition
table
a(1) = 1.
a(2) = 1.
a(N) = a(a(N-1))+a(N-a(N-1)).
% argmax: f... |
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... | #PicoLisp | PicoLisp | (de hofcon (N)
(cache '(NIL) N
(if (>= 2 N)
1
(+
(hofcon (hofcon (dec N)))
(hofcon (- N (hofcon (dec N)))) ) ) ) )
(scl 20)
(de sequence (M)
(let (Lim 4 Max 0 4k$ 0)
(for (N 3 (>= M N) (inc N))
(let V (*/ (hofcon N) 1.0 N)
(setq Max ... |
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 ... | #N.2Ft.2Froff | N/t/roff |
.tm 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 ... | #Neko | Neko | /**
Hello world, to standard error, in Neko
Tectonics:
nekoc hello-stderr.neko
neko hello-stderr
*/
/* Assume stderr is already open, just need write */
var file_write = $loader.loadprim("std@file_write", 4);
/* Load (and execute) the file_stderr primitive */
var stderr = $loader.loadprim("std@file_stde... |
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 ... | #Nemerle | Nemerle | System.Console.Error.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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "QSequen.bas"
110 LET LIMIT=1000
120 NUMERIC Q(1 TO LIMIT)
130 LET Q(1),Q(2)=1
140 FOR I=3 TO LIMIT
150 LET Q(I)=Q(I-Q(I-1))+Q(I-Q(I-2))
160 NEXT
170 PRINT "First 10 terms:"
180 FOR I=1 TO 10
190 PRINT Q(I);
200 NEXT
210 PRINT :PRINT "Term 1000:";Q(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... | #J | J | Qs=:0 1 1
Q=: verb define
n=. >./,y
while. n>:#Qs do.
Qs=: Qs,+/(-_2{.Qs){Qs
end.
y{Qs
) |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Aime | Aime | o_text("Hello world!\n"); |
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... | #Lua | Lua | -- Returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one
local function tryHt( a, b, c )
local result
local s = ( a + b + c ) / 2;
local areaSquared = s * ( s - a ) * ( s - b ) * ( s - c );
if areaSquared > 0 then
-- a, b, c does form a triangle
local are... |
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
| #Common_Lisp | Common Lisp | CL-USER> (defun add (a b) (+ a b))
ADD
CL-USER> (add 1 2)
3
CL-USER> (defun call-it (fn x y)
(funcall fn x y))
CALL-IT
CL-USER> (call-it #'add 1 2)
3 |
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... | #Panda | Panda | 8080.port.listen.say("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... | #Perl | Perl | use Socket;
my $port = 8080;
my $protocol = getprotobyname( "tcp" );
socket( SOCK, PF_INET, SOCK_STREAM, $protocol ) or die "couldn't open a socket: $!";
# PF_INET to indicate that this socket will connect to the internet domain
# SOCK_STREAM indicates a TCP stream, SOCK_DGRAM would indicate UDP communication
... |
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... | #Rust | Rust |
use std::collections::HashMap;
struct Hffs {
sequence_r: HashMap<usize, usize>,
sequence_s: HashMap<usize, usize>,
}
impl Hffs {
fn new() -> Hffs {
Hffs {
sequence_r: HashMap::new(),
sequence_s: HashMap::new(),
}
}
fn ffr(&mut self, n: usize) -> usize {
... |
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... | #Scala | Scala | object HofstadterFigFigSeq extends App {
import scala.collection.mutable.ListBuffer
val r = ListBuffer(0, 1)
val s = ListBuffer(0, 2)
def ffr(n: Int): Int = {
val ffri: Int => Unit = i => {
val nrk = r.size - 1
val rNext = r(nrk)+s(nrk)
r += rNext
(r(nrk)+2 to rNext-1).foreach{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... | #Potion | Potion | horner = (x, coef) :
result = 0
coef reverse each (a) :
result = (result * x) + a
.
result
.
horner(3, (-19, 7, -4, 6)) print |
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... | #PowerShell | PowerShell |
function horner($coefficients, $x) {
$accumulator = 0
foreach($i in ($coefficients.Count-1)..0){
$accumulator = ( $accumulator * $x ) + $coefficients[$i]
}
$accumulator
}
$coefficients = @(-19, 7, -4, 6)
$x = 3
horner $coefficients $x
|
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.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim c = a
a = b
b = c
End Sub
Structure Point
Dim x As Integer
Dim y As Integer
'rotate/flip a quadrant appropriately
Sub Rot(n As Integer, rx As Boolean, ry As Boole... |
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
... | #PL.2FI | PL/I | (subscriptrange, size, fofl):
Easter: procedure options (main);
declare months(12) character (9) varying static initial (
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December');
declare (year, month, day) fixe... |
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... | #Racket | Racket | #lang racket
;; print the table for a given latitude and longitude-offset,
;; given in degrees
(define (print-table lat long-offset)
;; print the table header
(display
(~a " sine of latitude: "
(~r (sin (deg->rad lat)) #:precision '(= 3))
"\n"
" diff longitude: "
(~r long-o... |
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... | #Raku | Raku | sub postfix:<°> ($a) { $a * pi / 180 } # degrees to radians
sub postfix:<®> ($a) { $a * 180 / pi } # radians to degrees
my $latitude = prompt 'Enter latitude => ';
my $longitude = prompt 'Enter longitude => ';
my $meridian = prompt 'Enter legal meridian => ';
my $lat_sin = sin( $latitude° );
say 'Sine ... |
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... | #Ruby | Ruby | require 'priority_queue'
def huffman_encoding(str)
char_count = Hash.new(0)
str.each_char {|c| char_count[c] += 1}
pq = CPriorityQueue.new
# chars with fewest count have highest priority
char_count.each {|char, count| pq.push(char, count)}
while pq.length > 1
key1, prio1 = pq.delete_min
key2, ... |
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
⋮
⋮
⋮
⋱
... | #VBA | VBA | Private Function Identity(n As Integer) As Variant
Dim I() As Integer
ReDim I(n - 1, n - 1)
For j = 0 To n - 1
I(j, j) = 1
Next j
Identity = I
End Function |
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 |... | #UNIX_Shell | UNIX Shell | #!/bin/ksh
# tested with ksh93s+
builtin printf
integer a=0
integer b=0
read a?"Enter value of a: " || { print -u2 "Input of a aborted." ; exit 1 ; }
read b?"Enter value of b: " || { print -u2 "Input of b aborted." ; exit 1 ; }
if (( a < b )) ; then
printf "%d is less than %d\n" a b
fi
if (( a == b )) ; the... |
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 |... | #Ursa | Ursa | decl int first second
out "enter first integer: " console
set first (in int console)
out "enter second integer: " console
set second (in int console)
if (= first second)
out "the two integers are equal" endl console
end if
if (< first second)
out first " is less than " second endl console
end if
if (... |
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.
| #LSL | LSL | string sURL = "http://www.RosettaCode.Org";
key kHttpRequestId;
default {
state_entry() {
kHttpRequestId = llHTTPRequest(sURL, [], "");
}
http_response(key kRequestId, integer iStatus, list lMetaData, string sBody) {
if(kRequestId==kHttpRequestId) {
llOwnerSay("Status="+(string)iStatus);
integer x = 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.
| #Lua | Lua |
local http = require("socket.http")
local url = require("socket.url")
local page = http.request('http://www.google.com/m/search?q=' .. url.escape("lua"))
print(page)
|
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... | #PL.2FI | PL/I |
/* First part: */
declare L (10000) fixed static initial ((1000) 0);
L(1), L(2) = 1;
do i = 3 to 10000;
k = L(i);
L(i) = L(i-k) + L(1+k);
end;
|
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... | #Python | Python | from __future__ import division
def maxandmallows(nmaxpower2):
nmax = 2**nmaxpower2
mx = (0.5, 2)
mxpow2 = []
mallows = None
# Hofstadter-Conway sequence starts at hc[1],
# hc[0] is not part of the series.
hc = [None, 1, 1]
for n in range(2, nmax + 1):
ratio = hc[n] / 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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
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 ... | #Nim | Nim | stderr.writeln "Hello 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 ... | #Oberon-2 | Oberon-2 |
MODULE HelloErr;
IMPORT Err;
BEGIN
Err.String("Goodbye, World!");Err.Ln
END HelloErr.
|
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 ... | #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main()
{
fprintf(stderr, "Goodbye, World!\n");
fputs("Goodbye, World!\n", stderr);
NSLog(@"Goodbye, World!");
return 0;
} |
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... | #Java | Java | import java.util.HashMap;
import java.util.Map;
public class HofQ {
private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{
put(1, 1);
put(2, 1);
}};
private static int[] nUses = new int[100001];//not part of the task
public static int Q(int n){
nUses[n]++;//not part of the task
if(... |
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
| #Algae | Algae | printf("Hello world!\n"); |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Heron]
Heron[a_, b_, c_] := With[{s = (a + b + c)/2}, Sqrt[s (s - a) (s - b) (s - c)]]
PrintTemporary[Dynamic[{a, b, c}]];
results = Reap[
Do[
If[a < b + c \[And] b < c + a \[And] c < a + b,
If[GCD[a, b, c] == 1,
If[IntegerQ[Heron[a, b, c]],
Sow[<|"Sides" -> {a, b, c}, "Area" -> H... |
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... | #Nim | Nim | import math, algorithm, lenientops, strformat, sequtils
type HeronianTriangle = tuple[a, b, c: int; p: int; area: int]
func `$` (t: HeronianTriangle): string =
fmt"{t.a:3d}, {t.b:3d}, {t.c:3d} {t.p:7d} {t.area:8d}"
func hero(a, b, c: int): float =
let s = (a + b + c) / 2
result = sqrt(s * (s - a) * (s - 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
| #Cowgol | Cowgol | include "cowgol.coh";
# In order to pass functions around, you must first define an interface.
# This is similar to a delegate in C#; it becomes a function pointer type.
# This interface takes two integers and returns one.
interface Dyadic(x: int32, y: int32): (r: int32);
# For a function to be able to be passed ar... |
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... | #Phix | Phix | -- demo\rosetta\SimpleHttpServer.exw
without js
include builtins\sockets.e
constant MAX_QUEUE = 100,
ESCAPE = #1B,
response = substitute("""
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
<!DOCTYPE html>
<html>
<head>
<title>Bye-bye baby bye-bye</title>
<style>
body { ba... |
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... | #Sidef | Sidef | var r = [nil, 1]
var s = [nil, 2]
func ffsr(n) {
while(r.end < n) {
r << s[r.end]+r[-1]
s << [(s[-1]+1 .. r[-1]-1)..., r[-1]+1].grep{ s[-1] < _ }...
}
return n
}
func ffr(n) { r[ffsr(n)] }
func ffs(n) { s[ffsr(n)] }
printf(" i: R(i) S(i)\n")
printf("==============\n")
{ |i|
printf("%3d: %3d %... |
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... | #Prolog | Prolog | horner([], _X, 0).
horner([H|T], X, V) :-
horner(T, X, V1),
V is V1 * X + H.
|
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... | #PureBasic | PureBasic | Procedure Horner(List Coefficients(), b)
Define result
ForEach Coefficients()
result*b+Coefficients()
Next
ProcedureReturn result
EndProcedure |
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.
| #Wren | Wren | import "graphics" for Canvas, Color, Point
import "dome" for Window
class Game {
static init() {
Window.title = "Hilbert curve"
Canvas.resize(650, 650)
Window.resize(650, 650)
__points = []
__width = 64
hilbert(0, 0, __width, 0, 0)
var col = Color.hex("#90EE... |
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
... | #PowerShell | PowerShell |
function Get-Easter
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[int]
$Year
)
Begin
{
... |
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... | #REXX | REXX | /*REXX program displays: hour, sun hour angle, dial hour line angle, 6am ───► 6pm. */
numeric digits length( pi() ) - length(.) /*in case sundial is in polar regions. */
parse arg lat lng . /*obtain optional arguments from the CL*/
/* ┌─────────... |
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... | #Rust | Rust |
use std::collections::BTreeMap;
use std::collections::binary_heap::BinaryHeap;
#[derive(Debug, Eq, PartialEq)]
enum NodeKind {
Internal(Box<Node>, Box<Node>),
Leaf(char),
}
#[derive(Debug, Eq, PartialEq)]
struct Node {
frequency: usize,
kind: NodeKind,
}
impl Ord for Node {
fn cmp(&self, rhs... |
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
⋮
⋮
⋮
⋱
... | #VBScript | VBScript |
build_matrix(7)
Sub build_matrix(n)
Dim matrix()
ReDim matrix(n-1,n-1)
i = 0
'populate the matrix
For row = 0 To n-1
For col = 0 To n-1
If col = i Then
matrix(row,col) = 1
Else
matrix(row,col) = 0
End If
Next
i = i + 1
Next
'display the matrix
For row = 0 To n-1
For col = 0 To n-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 |... | #V | V | [compare
[ [>] ['less than' puts]
[<] ['greater than' puts]
[=] ['is equal' puts]
] when].
|2 3 compare
greater than
|3 2 compare
less than
|2 2 compare
is equal |
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 |... | #Vala | Vala |
void main(){
int a;
int b;
stdout.printf("Please type in int 1\n");
a = int.parse(stdin.read_line());
stdout.printf("Please type in int 2\n");
b = int.parse(stdin.read_line());
if (a < b)
stdout.printf("%d is less than %d\n", a, b);
if (a == b)
stdout.printf("%d i... |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Declare xml "Microsoft.XMLHTTP"
const testUrl$ = "http://www.rosettacode.org"
With xml, "readyState" as ReadyState
Method xml "Open", "Get", testUrl$, True ' True means Async
Method xml "send"
\\ We set a thread to count time
k=0
Thread {
... |
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.
| #Maple | Maple |
content := URL:-Get( "http://www.google.com/" );
|
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... | #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ ' [ 1 1 ]
swap 2 - times
[ dup -1 peek 2dup 1 - peek
dip [ dip dup negate peek ]
+ join ] ] is hof-con ( n --> [ )
[ behead do rot
witheach
[ do 2over 2over v- v0<
if 2swap
2drop ] ] ... |
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... | #R | R | f = local(
{a = c(1, 1)
function(n)
{if (is.na(a[n]))
a[n] <<- f(f(n - 1)) + f(n - f(n - 1))
a[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 ... | #OCaml | OCaml | prerr_endline "Goodbye, World!"; (* this is how you print a string with newline to stderr *)
Printf.eprintf "Goodbye, World!\n"; (* this is how you would use printf with stderr *) |
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 ... | #Octave | Octave | 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 ... | #Oforth | Oforth | System.Err "Goodbye, World!" << cr |
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 ... | #Ol | Ol |
(print-to 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... | #JavaScript | JavaScript | var hofstadterQ = function() {
var memo = [1,1,1];
var Q = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = Q(n - Q(n-1)) + Q(n - Q(n-2));
memo[n] = result;
}
return result;
};
return Q;
}();
for (var i = 1; i <=10; i += 1) {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.