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/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.D... |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.D... |
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... | #ALGOL_W | ALGOL W | begin
% record to hold details of a Heronian triangle %
record Heronian ( integer a, b, c, area, perimeter );
% returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one %
reference(Heronian) procedure tryHt( integer value a, b, c ) ;
begin
real s,... |
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... | #AppleScript | AppleScript | use framework "Foundation"
-- HERONIAN TRIANGLES --------------------------------------------------------
-- heroniansOfSideUpTo :: Int -> [(Int, Int, Int)]
on heroniansOfSideUpTo(n)
script sideA
on |λ|(a)
script sideB
on |λ|(b)
script sideC
... |
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
| #Aime | Aime | integer
average(integer p, integer q)
{
return (p + q) / 2;
}
void
out(integer p, integer q, integer (*f) (integer, integer))
{
o_integer(f(p, q));
o_byte('\n');
}
integer
main(void)
{
# display the minimum, the maximum and the average of 117 and 319
out(117, 319, min);
out(117, 319, max... |
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... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SOCKLIB"
PROC_initsockets
maxSess% = 8
DIM sock%(maxSess%-1), rcvd$(maxSess%-1), Buffer% 255
ON ERROR PRINT REPORT$ : PROC_exitsockets : END
ON CLOSE PROC_exitsockets : QUIT
port$ = "8080"
host$ = FN_gethostname
PRINT "Host name is " host$
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Bye-... |
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 ... | #BASIC256 | BASIC256 |
text1$ = " " & chr(10) & "<<#FOO# " & chr(10) & " #jaja#, `esto`" & chr(10) & " <simula>" & chr(10) & " \un\" & chr(10) & " ${ejemplo} de 'heredoc'" & chr(10) & " en BASIC256."
text2$ = "Esta es la primera linea." & chr(10) & "Esta es la segunda linea." & chr(10) & "Esta 'linea' contiene comillas."
print tex... |
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 ... | #Blade | Blade | echo 'All strings
support
multiline
in Blade' |
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 ... | #C.23 | C# | using System;
class Program
{
static void Main(string[] args)
{
Console.Write(@"
multiline
strings are easy
to put together
in C#");
}
} |
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 ... | #C.2B.2B | C++ | #include <iostream> // Only for cout to demonstrate
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it ca... |
http://rosettacode.org/wiki/History_variables | History variables | Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.
History variables are variables in a programming la... | #Kotlin | Kotlin | // version 1.1.4
class HistoryVariable<T>(initialValue: T) {
private val history = mutableListOf<T>()
var currentValue: T
get() = history[history.size - 1]
set(value) {
history.add(value)
}
init {
currentValue = initialValue
}
fun showHistory() {
... |
http://rosettacode.org/wiki/History_variables | History variables | Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.
History variables are variables in a programming la... | #Lua | Lua | -- History variables in Lua 6/12/2020 db
local HistoryVariable = {
new = function(self)
return setmetatable({history={}},self)
end,
get = function(self)
return self.history[#self.history]
end,
set = function(self, value)
self.history[#self.history+1] = value
end,
undo = function(self)
self... |
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... | #F.23 | F# |
// Populate R and S with values of Hofstadter Figure Figure sequence. Nigel Galloway: August 28th., 2020
let fF q=let R,S=Array.zeroCreate<int>q,Array.zeroCreate<int>q
R.[0]<-1;S.[0]<-2
let rec fN n g=match n=q with true->(R,S)
|_->R.[n]<-R.[n-1]+S.[n-1]
... |
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation | Horner's rule for polynomial evaluation | A fast scheme for evaluating a polynomial such as:
−
19
+
7
x
−
4
x
2
+
6
x
3
{\displaystyle -19+7x-4x^{2}+6x^{3}\,}
when
x
=
3
{\displaystyle x=3\;}
.
is to arrange the computation as follows:
(
(
(
(
0
)
x
+
6
)
x
+
(
−
4
)
)
x
+
7
)
x
+
(
−
19
)
{\displaystyle ((((0)x+6)x+(-4))x... | #Go | Go | package main
import "fmt"
func horner(x int64, c []int64) (acc int64) {
for i := len(c) - 1; i >= 0; i-- {
acc = acc*x + c[i]
}
return
}
func main() {
fmt.Println(horner(3, []int64{-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... | #Groovy | Groovy | def hornersRule = { coeff, x -> coeff.reverse().inject(0) { accum, c -> (accum * x) + c } } |
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.
| #Go | Go | package main
import "github.com/fogleman/gg"
var points []gg.Point
const width = 64
func hilbert(x, y, lg, i1, i2 int) {
if lg == 1 {
px := float64(width-x) * 10
py := float64(width-y) * 10
points = append(points, gg.Point{px, py})
return
}
lg >>= 1
hilbert(x+i1*l... |
http://rosettacode.org/wiki/Honeycombs | Honeycombs | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | hexagon[{x_, y_}] :=
Polygon[Transpose[{{1/2, 1/4, -1/4, -1/2, -1/4, 1/4} +
x, {0, Sqrt[3]/4, Sqrt[3]/4, 0, -Sqrt[3]/4, -Sqrt[3]/4} + y}]];
off = Transpose[{ConstantArray[0, 20], {0, 0, 0, 0, Sqrt[3]/4,
Sqrt[3]/4, Sqrt[3]/4, Sqrt[3]/4, 0, 0, 0, 0, Sqrt[3]/4,
Sqrt[3]/4, Sqrt[3]/4, Sqrt[3]/4, 0, 0, ... |
http://rosettacode.org/wiki/Honeycombs | Honeycombs | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position... | #MATLAB | MATLAB | function Honeycombs
nRows = 4; % Number of rows
nCols = 5; % Number of columns
nHexs = nRows*nCols; % Number of hexagons
rOuter = 1; % Circumradius
startX = 0; % x-coordinate of upper left hexagon
startY... |
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
... | #Factor | Factor | USING: calendar formatting io kernel locals math math.ranges
sequences ;
! Calculate Easter.
:: my-easter ( year -- timestamp )
year 19 mod :> a
year 100 /i :> b
year 100 mod :> c
b 4 /i :> d
b 4 mod ... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
PrintSundial(-4.95, -150.5, -150);
end
procedure PrintSundial(lat, lng, mer )
write("latitude: ", lat,
"\nlongitude: ", lng,
"\nlegal meridian: ", mer)
slat := sin(dtor(lat))
write("sine of latitude: ",slat,
"\ndiff longitude: ", lng-mer)
... |
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... | #Nim | Nim | import tables, sequtils
type
# Following range can be changed to produce Huffman codes on arbitrary alphabet (e.g. ternary codes)
CodeSymbol = range[0..1]
HuffCode = seq[CodeSymbol]
Node = ref object
f: int
parent: Node
case isLeaf: bool
of true:
c: char
else:
childs: arr... |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #REBOL | REBOL | print system/network/host |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #REXX | REXX | say value('COMPUTERNAME',,"ENVIRONMENT")
say value('OS',,"ENVIRONMENT") |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Ruby | Ruby | require 'socket'
host = Socket.gethostname |
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
⋮
⋮
⋮
⋱
... | #Quackery | Quackery | [ [] swap times
[ 0 i^ of 1 join 0 i of
join nested join ] ] is identity ( n --> [ )
5 identity echo |
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
⋮
⋮
⋮
⋱
... | #R | R | diag(3) |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #TXR | TXR | @(do (defun inc-num-str (str-in)
(let ((len (length str-in))
(str (copy-str str-in)))
(for ((i (- len 1)))
((>= i 0) `1@str`)
((dec i))
(if (<= (inc [str i]) #\9)
(return str)
(set [str i] #\0))))))
@(bind a @(inc-num-str "999... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #UNIX_Shell | UNIX Shell | # All variables are strings within the shell
# Although num look like a number, it is in fact a numerical string
num=5
num=`expr $num + 1` # Increment the number |
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 |... | #Raku | Raku | my $a = prompt("1st int: ").floor;
my $b = prompt("2nd int: ").floor;
if $a < $b {
say 'Less';
}
elsif $a > $b {
say 'Greater';
}
elsif $a == $b {
say '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 |... | #Raven | Raven | "Enter the first number: " print
expect trim 1.1 prefer as $a
"Enter the second number: " print
expect trim 1.1 prefer as $b
$a $b < if $b $a "%g is less than %g\n" print
$a $b > if $b $a "%g is greater than %g\n" print
$a $b = if $b $a "%g is equal to %g\n" print |
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.
| #Emacs_Lisp | Emacs Lisp | (let ((buffer (url-retrieve-synchronously "http://www.rosettacode.org")))
(unwind-protect
(with-current-buffer buffer
(message "%s" (buffer-substring url-http-end-of-headers (point-max))))
(kill-buffer buffer))) |
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... | #Euler_Math_Toolbox | Euler Math Toolbox |
>function hofstadter (n) ...
$v=ones(1,n);
$ loop 2 to n-1
$ k=v{#};
$ v{#+1}=v{k}+v{#-k+1};
$ end
$ return v
$endfunction
>v=hofstadter(2^20);
>k=1:256; plot2d(v[k]/k):
>function hsmaxima (v,k) ...
$ w=zeros(1,k);
$ for j=1 to k
$ i=2^(j-1):2^j;
$ w[j]=max(v[i]/i);
$ end;
$ return w;
$endfunction
... |
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... | #F.23 | F# | let a = ResizeArray[0; 1; 1]
while a.Count <= (1 <<< 20) do
a.[a.[a.Count - 1]] + a.[a.Count - a.[a.Count - 1]] |> a.Add
for p = 1 to 19 do
Seq.max [|for i in 1 <<< p .. 1 <<< p+1 -> float a.[i] / float i|]
|> printf "Maximum in %6d..%7d is %g\n" (1 <<< p) (1 <<< p+1)
let mallows, _ = a
|> List.... |
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 ... | #AutoIt | AutoIt | ConsoleWriteError("Goodbye, World!" & @CRLF) |
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 ... | #Avail | Avail | 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 ... | #AWK | AWK | BEGIN {
print "Goodbye, World!"| "cat 1>&2"
} |
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... | #CLU | CLU | q_seq = proc (n: int) returns (sequence[int])
q: array[int] := array[int]$[1,1]
for i: int in int$from_to(3,n) do
array[int]$addh(q, q[i-q[i-1]] + q[i-q[i-2]])
end
return(sequence[int]$a2s(q))
end q_seq
start_up = proc ()
po: stream := stream$primary_output()
q: sequence[int] := q_se... |
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... | #CoffeeScript | CoffeeScript | hofstadterQ = do ->
memo = [ 1 ,1, 1]
Q = (n) ->
result = memo[n]
if typeof result != 'number'
result = memo[n] = Q(n - Q(n - 1)) + Q(n - Q(n - 2))
result
# some results:
console.log 'Q(' + i + ') = ' + hofstadterQ(i) for i in [1..10]
console.log 'Q(1000) = ' + hofstadterQ(1000) |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #Haskell | Haskell | import Data.Number.CReal -- from numbers
import qualified Data.Number.CReal as C
hickerson :: Int -> C.CReal
hickerson n = (fromIntegral $ product [1..n]) / (2 * (log 2 ^ (n + 1)))
charAfter :: Char -> String -> Char
charAfter ch string = ( dropWhile (/= ch) string ) !! 1
isAlmostInteger :: C.CReal -> Bool
isAl... |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #J | J | ln2=: [: +/ 1 % [: (*2x&^) 1+i.
h=: ! % 2*(ln2 99)^>: |
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... | #AutoHotkey | AutoHotkey | Primitive_Heronian_triangles(MaxSide){
obj :=[]
loop, % MaxSide {
a := A_Index
loop % MaxSide-a+1 {
b := A_Index+a-1
loop % MaxSide-b+1 {
c := A_Index+b-1, s := (a+b+c)/2, Area := Sqrt(s*(s-a)*(s-b)*(s-c))
if (Area = Floor(Area)) && (Area>0) && !obj[a/s, b/s, c/s]
obj[a/s, b/s, c/s]:=1 ,res .= ... |
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
| #ALGOL_68 | ALGOL 68 | PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL:
(
f(1) + 2
);
PROC second = (LONG REAL x)LONG REAL:
(
x/2
);
main: (
printf(($xg(5,2)l$,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... | #C.23 | C# | using System.Text;
using System.Net.Sockets;
using System.Net;
namespace WebServer
{
class GoodByeWorld
{
static void Main(string[] args)
{
const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n";
const int port = 8080;
bool ... |
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... | #C.2B.2B | C++ | (ns goodbye-world.handler
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
[compojure.route :as route]))
(defroutes app-routes
(GET "/" [] "Goodbye, World!")
(route/resources "/")
(route/not-found "Not Found"))
(def app
(handler/site app-routes)) |
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 ... | #Clojure | Clojure | myDoc = '''
Single-quoted heredocs allows no '#{foo}' interpolation.
This behavior is similar to single-quoted strings.
'''
doc2 = """
However, double-quoted heredocs *do* allow these.
See it in action:
Content: "#{myDoc}"
"""
console.log doc2 |
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 ... | #CoffeeScript | CoffeeScript | myDoc = '''
Single-quoted heredocs allows no '#{foo}' interpolation.
This behavior is similar to single-quoted strings.
'''
doc2 = """
However, double-quoted heredocs *do* allow these.
See it in action:
Content: "#{myDoc}"
"""
console.log doc2 |
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 ... | #Common_Lisp | Common Lisp | ;; load cl-heredoc with QuickLisp
(ql:quickload 'cl-heredoc)
;; use #>xxx>yyyyyyyy!xxx as read-macro for heredoc
(set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
;; example:
(format t "~A~%" #>eof1>Write whatever (you) "want",
no matter how many lines or what characters until
the magic end sequenc... |
http://rosettacode.org/wiki/History_variables | History variables | Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.
History variables are variables in a programming la... | #M2000_Interpreter | M2000 Interpreter |
Flush ' empty curtrent stack
\\ a is a pointer to a new stack object
a=stack:=1,2@,3%
Print Len(A)=3
For i=1 to Len(a) {
Print StackType$(a, i)="Number"
}
b=stack
Print len(b)=0
Push 1, 2 \\ to current stack
Stack b {
\\ make b the current stack
Data 1, 2, 3
} ' Data add to bottom
\\ now current st... |
http://rosettacode.org/wiki/History_variables | History variables | Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.
History variables are variables in a programming la... | #Nim | Nim | type HistoryVar[T] = object
hist: seq[T]
ffunc initHistoryVar[T](value: T = T.default): HistoryVar[T] =
## Initialize a history variable with given value.
result.hist.add value
func set(h: var HistoryVar; value: h.T) =
## Set the history variable to given value.
h.hist.add value
func get(h: HistoryVar):... |
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... | #Factor | Factor | SYMBOL: S V{ 2 } S set
SYMBOL: R V{ 1 } R set
: next ( s r -- news newr )
2dup [ last ] bi@ + suffix
dup [
[ dup last 1 + dup ] dip member? [ 1 + ] when suffix
] dip ;
: inc-SR ( n -- )
dup 0 <=
[ drop ]
[ [ S get R get ] dip [ next ] times R set S set ]
if ;
: ffs ( n -- S(n) )
dup S get length - inc-SR
1 ... |
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... | #FreeBASIC | FreeBASIC | function ffr( n as integer ) as integer
if n = 1 then return 1
dim as integer i, j, r=1, s=1, v(1 to 2*n+1)
v(1) = 1
for i = 2 to n
for j = s to 2*n
if v(j) = 0 then exit for
next j
v(j) = 1
s = j
r += s
if r <= 2*n then v(r) = 1
next i
... |
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... | #Haskell | Haskell | horner :: (Num a) => a -> [a] -> a
horner x = foldr (\a b -> a + b*x) 0
main = print $ 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... | #HicEst | HicEst | REAL :: x=3, coeffs(4)
DATA coeffs/-19.0, 7.0, -4.0, 6.0/
WRITE(Messagebox) Horner(coeffs, x) ! shows 128
FUNCTION Horner(c, x)
DIMENSION c(1)
Horner = 0
DO i = LEN(c), 1, -1
Horner = x*Horner + c(i)
ENDDO
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.
| #Haskell | Haskell | import Data.Bool (bool)
import Data.Tree
rule :: Char -> String
rule c =
case c of
'a' -> "daab"
'b' -> "cbba"
'c' -> "bccd"
'd' -> "addc"
_ -> []
vectors :: Char -> [(Int, Int)]
vectors c =
case c of
'a' -> [(-1, 1), (-1, -1), (1, -1), (1, 1)]
'b' -> [(1, -1), (-1, -1), (-1, 1), (1,... |
http://rosettacode.org/wiki/Honeycombs | Honeycombs | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position... | #Nim | Nim | import lenientops, math, random, sequtils, strutils, tables
import gintro/[gobject, gdk, gtk, gio, cairo]
import gintro/glib except PI
const
Size = 308 # Size of drawing area.
NHexagons = 20 # Number of hexagons.
Radius = 30.0
XOffset = 1 + sin(PI / 6)
YOffset = cos(PI / 6)
... |
http://rosettacode.org/wiki/Honeycombs | Honeycombs | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position... | #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use Tk;
use List::Util qw(shuffle);
sub altitude {
sqrt(3/4) * shift;
}
sub polygon_coordinates {
my ($x, $y, $size) = @_;
my $alt = altitude($size);
return ($x - $size, $y,
$x - ($size / 2), $y - $alt,
$x + ($size / 2), $... |
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
... | #Forth | Forth |
variable year
: ea_a year @ 19 mod ;
: ea_b year @ 100 / ;
: ea_c year @ 100 mod ;
: ea_d ea_b 4 / ;
: ea_e ea_b 4 mod ;
: ea_f ea_b 8 + 25 / ;
: ea_g ea_b ea_f - 1 + 3 / ;
: ea_h 19 ea_a * ea_b + ea_d - ea_g - 15 + 30 mod ;
: ea_i ea_c 4 / ;
: ea_k ea_c 4 mod ;
: ea_l 32 2 ea_e * + 2 ea_i * + ea_h - ea_k - 7 mod ;... |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "SunDial.bas"
110 OPTION ANGLE RADIANS
120 TEXT 80
130 LET DR=PI/180:LET RD=180/PI
140 INPUT PROMPT "Enter latitude: ":LAT
150 INPUT PROMPT "Enter longitude: ":LNG
160 INPUT PROMPT "Enter legal meridian: ":REF
170 LET S=SIN(LAT*DR)
180 PRINT :PRINT "Sine of latitude :";S
190 PRINT "Diff longitude: ";LNG-RE... |
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... | #J | J | require 'trig'
atan2=: {:@*.@j. NB. arc tangent of y divided by x
horiz=: verb define
'lat lng ref'=. y
out=. smoutput@,&":
'Latitude ' out lat
'Longitude ' out lng
'Legal meridian ' out ref
'Sine of latitude ' out slat=. sin rfd lat
'Diff longitude ' out -diff=. ref - lng
lbl=.'hou... |
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... | #Oberon-2 | Oberon-2 |
MODULE HuffmanEncoding;
IMPORT
Object,
PriorityQueue,
Strings,
Out;
TYPE
Leaf = POINTER TO LeafDesc;
LeafDesc = RECORD
(Object.ObjectDesc)
c: CHAR;
END;
Inner = POINTER TO InnerDesc;
InnerDesc = RECORD
(Object.ObjectDesc)
left,right: Object.Object;
END;
VAR
str: ARRAY 128 OF... |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Run_BASIC | Run BASIC | print Platform$ ' OS where Run BASIC is being hosted
print UserInfo$ ' Information about the user's web browser
print UserAddress$ ' IP address of the user |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Rust | Rust | fn main() {
match hostname::get_hostname() {
Some(host) => println!("hostname: {}", host),
None => eprintln!("Could not get hostname!"),
}
} |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Scala | Scala | println(java.net.InetAddress.getLocalHost.getHostName) |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Scheme | Scheme | (use posix)
(get-host-name) |
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
⋮
⋮
⋮
⋱
... | #Racket | Racket |
#lang racket
(require math)
(identity-matrix 5)
|
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Raku | Raku | sub identity-matrix($n) {
my @id;
for flat ^$n X ^$n -> $i, $j {
@id[$i][$j] = +($i == $j);
}
@id;
}
.say for identity-matrix(5); |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #Ursa | Ursa | decl string num
set num "123"
set num (int (+ (int num) 1)) |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #Ursala | Ursala | #import nat
instring = ~&h+ %nP+ successor+ %np@iNC # convert, do the math, convert back |
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 |... | #REBOL | REBOL |
rebol [
Title: "Comparing Two Integers"
URL: http://rosettacode.org/wiki/Comparing_two_integers
]
a: ask "First integer? " b: ask "Second integer? "
relation: [
a < b "less than"
a = b "equal to"
a > b "greater than"
]
print [a "is" case relation 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 |... | #Red | Red | Red [
Title: "Comparing Two Integers"
URL: http://rosettacode.org/wiki/Comparing_two_integers
Date: 2021-10-25
]
a: to-integer ask "First integer? " b: to-integer ask "Second integer? "
relation: [
a < b "less than"
a = b "equal to"
a > b "greater than"
]
print [a "is" case relation 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.
| #Erlang | Erlang |
-module(main).
-export([main/1]).
main([Url|[]]) ->
inets:start(),
case http:request(Url) of
{ok, {_V, _H, Body}} -> io:fwrite("~p~n",[Body]);
{error, Res} -> io:fwrite("~p~n", [Res])
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... | #Factor | Factor | USING: combinators formatting io kernel locals math math.ranges
prettyprint sequences splitting ;
MEMO:: a ( n -- a(n) ) ! memoize the recurrence relation
n {
{ 1 [ 1 ] }
{ 2 [ 1 ] }
[ 1 - a a n n 1 - a - a + ]
} case ;
20 2^ [1,b] [ [ a ] [ 1 + / ] bi* ] map-index
[
{ 1/2 } spl... |
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... | #Fortran | Fortran |
program conway
implicit none
integer :: a(2**20) ! The sequence a(n)
real :: b(2**20) ! The sequence a(n)/n
real :: v ! Max value in the range [2*i, 2**(i+1)]
integer :: nl(1) ! The location of v in the array b(n)
integer :: i, N, first, second, last, m
! Populate a(n) and b(n)
a... |
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 ... | #BASIC | BASIC |
ON ERROR GOTO ManejoErrores
ERROR 99
END
ManejoErrores:
PRINT "Googbye World!"
RESUME
|
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 ... | #Batch_File | Batch File | 1>&2 echo 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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Q-SEQ.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 SEQ.
02 Q PIC 9(3) OCCURS 1000 TIMES.
02 Q-TMP1 PIC 9(3).
02 Q-TMP2 PIC 9(3).
02 N PIC 9(4).
01 DISPLAYING.
... |
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers | Hickerson series of almost integers | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered 51.)
The function is:
h
(
n
)
=
n
!
2
(
ln
2
)
n
+
1
{\displaystyle h(n)={\operatorname {n} ! \ove... | #Java | Java | import java.math.*;
public class Hickerson {
final static String LN2 = "0.693147180559945309417232121458";
public static void main(String[] args) {
for (int n = 1; n <= 17; n++)
System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
}
static boolean almostInte... |
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... | #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
typedef struct{
int a,b,c;
int perimeter;
double area;
}triangle;
typedef struct elem{
triangle t;
struct elem* next;
}cell;
typedef cell* list;
void addAndOrderList(list *a,triangle t){
list iter,temp;
int flag = 0;
if(*a==NULL){
*a = (list)ma... |
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
| #AmigaE | AmigaE | PROC compute(func, val)
DEF s[10] : STRING
WriteF('\s\n', RealF(s,func(val),4))
ENDPROC
PROC sin_wrap(val) IS Fsin(val)
PROC cos_wrap(val) IS Fcos(val)
PROC main()
compute({sin_wrap}, 0.0)
compute({cos_wrap}, 3.1415)
ENDPROC |
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... | #Clojure | Clojure | (ns goodbye-world.handler
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
[compojure.route :as route]))
(defroutes app-routes
(GET "/" [] "Goodbye, World!")
(route/resources "/")
(route/not-found "Not Found"))
(def app
(handler/site app-routes)) |
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... | #Common_Lisp | Common Lisp | (ql:quickload :hunchentoot)
(defpackage :hello-web (:use :cl :hunchentoot))
(in-package :hello-web)
(define-easy-handler (hello :uri "/") () "Goodbye, World!")
(defparameter *server* (hunchentoot:start (make-instance 'hunchentoot:easy-acceptor :port 8080))) |
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 ... | #Crystal | Crystal | puts <<-DOC
this is a heredoc
it preserves indents and newlines
the DOC identifier is completely arbitrary
it can be lowercase, a keyword, or even a number (but not a float)
DOC |
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 ... | #D | D | import std.stdio, std.string;
void main() {
// Delimited strings: a 'q' followed by double quotes and an
// opening and closing delimiter of choice:
q"[a string that you "don't" have to escape]"
.writeln;
// If the delimiter is an identifier, the identifier must be
// immediately followed ... |
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 ... | #DWScript | DWScript | PrintLn("This is
a multiline
""string""
sample"); |
http://rosettacode.org/wiki/History_variables | History variables | Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.
History variables are variables in a programming la... | #Oberon-2 | Oberon-2 |
MODULE HVar;
IMPORT Out, Conv;
TYPE
(* Generic Object *)
Object* = POINTER TO ObjectDesc;
ObjectDesc = RECORD
Show: PROCEDURE(o:Object);
AsString: PROCEDURE(o: Object; VAR str: ARRAY OF CHAR);
END;
(* Integers *)
Integer = POINTER TO IntegerDesc;
IntegerDesc = RECORD (ObjectDesc)
val: INTEGER;
END;
... |
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... | #Go | Go | package main
import "fmt"
var ffr, ffs func(int) int
// The point of the init function is to encapsulate r and s. If you are
// not concerned about that or do not want that, r and s can be variables at
// package level and ffr and ffs can be ordinary functions at package level.
func init() {
// task 1, 2
... |
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... | #Icon_and_Unicon | Icon and Unicon |
procedure poly_eval (x, coeffs)
accumulator := 0
every index := *coeffs to 1 by -1 do
accumulator := accumulator * x + coeffs[index]
return accumulator
end
procedure main ()
write (poly_eval (3, [-19, 7, -4, 6]))
end
|
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... | #J | J |
horner =: (#."0 _ |.)~ NB. Tacit
horner =: [: +`*/ [: }: ,@,. NB. Alternate tacit (equivalent)
horner =: 4 : ' (+ *&y)/x' NB. Alternate explicit (equivalent)
|
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.
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Hilbert.bas"
110 OPTION ANGLE DEGREES
120 GRAPHICS HIRES 2
130 LET N=5:LET P=1:LET S=11*2^(6-N)
140 PLOT 940,700,ANGLE 180;
150 CALL HILBERT(S,N,P)
160 DEF HILBERT(S,N,P)
170 IF N=0 THEN EXIT DEF
180 PLOT LEFT 90*P;
190 CALL HILBERT(S,N-1,-P)
200 PLOT FORWARD S;RIGHT 90*P;
210 CALL HILBERT(S,N-1,... |
http://rosettacode.org/wiki/Hilbert_curve | Hilbert curve |
Task
Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
| #J | J | iter=: (, 1 , +@|.) @: (,~ 0j_1 ,~ 0j_1*|.)
hilbert=: {{0j1+(%{:) +/\0,iter ^: y ''}}
|
http://rosettacode.org/wiki/Honeycombs | Honeycombs | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position... | #Phix | Phix | include ..\arwen\arwen.ew
include ..\arwen\axtra.ew
constant N = 5, -- columns
M = 4, -- rows
cLetter = Yellow, -- initial colour(!)
cChosen = Purple,
cPlayr2 = Purple, -- (2 player if!=c_Chosen)
cHover = White,
cLines = Black,
cSelect = Black, -- (... |
http://rosettacode.org/wiki/Honeycombs | Honeycombs | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position... | #Prolog | Prolog | honeycomb :-
new(W, window('Honeycomb')),
new(Counter, counter(20)),
new(Ph, phrase(W, point(50,500))),
send(W, recogniser, new(KB, key_binding(@nil, argument))),
numlist(0, 19, NL),
create_letters(20, [], LL),
maplist(build_list(150,100), NL, LP),
new(ChCell, chain),
maplist(create_cell(W, Counter, Ph,... |
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
... | #Fortran | Fortran | subroutine easter(year,month,day)
c Easter sunday
c
c Input
c year
c Output
c month
c day
c
c See:
c Jean Meeus, "Astronomical Formulae for Calculators",
c 4th edition, Willmann-Bell, 1988, p.31
implicit integer(a-z)
a=mod(year,19)
b=year/100
c=mod(year,100)
d=b/4
e=mod(b... |
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... | #Java | Java | import java.util.Scanner;
public class Sundial {
public static void main(String[] args) {
double lat, slat, lng, ref;
Scanner sc = new Scanner(System.in);
System.out.print("Enter latitude: ");
lat = sc.nextDouble();
System.out.print("Enter longitude: ");
lng = sc.... |
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... | #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface HuffmanTree : NSObject {
int freq;
}
-(instancetype)initWithFreq:(int)f;
@property (nonatomic, readonly) int freq;
@end
@implementation HuffmanTree
@synthesize freq; // the frequency of this tree
-(instancetype)initWithFreq:(int)f {
if (self = [super init]) {
freq ... |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "socket.s7i";
const proc: main is func
begin
writeln(getHostname);
end func; |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Sidef | Sidef | var sys = frequire('Sys::Hostname');
var host = sys.hostname; |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Slate | Slate | Platform current nodeName |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Smalltalk | Smalltalk | OperatingSystem getHostName |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.