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/General_FizzBuzz | General FizzBuzz | Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ... | #Java | Java | public class FizzBuzz {
public static void main(String[] args) {
Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")};
for (int i = 1; i <= 20; i++) {
StringBuilder sb = new StringBuilder();
for (Sound sound : sounds) {
sb.app... |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #Z80_Assembly | Z80 Assembly | ;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
read "\SrcALL\winapeBuildCompat.asm"
;;;;;;;;;;;;;;;;;;; PROGRAM ;;;;;;;;;;;;;;;;;;;
org &8000
ld de,27
call doHailstone
;returns length of sequence, and writes each entry in the sequence
; to RAM
;print... |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #Delphi | Delphi | program atoz;
var
ch : char;
begin
for ch in ['a'..'z'] do
begin
write(ch);
end;
end. |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #Draco | Draco | /* Generate the lowercase alphabet and store it in a buffer */
proc alph(*char buf) *char:
channel output text ch;
char letter;
open(ch, buf);
for letter from 'a' upto 'z' do
write(ch; letter)
od;
close(ch);
buf
corp
/* Use the function to print the alphabet */
proc main() void:
... |
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
| #Ol | Ol | (print "Hello world!") |
http://rosettacode.org/wiki/Generator/Exponential | Generator/Exponential | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the objec... | #Kotlin | Kotlin | // version 1.1.0
// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning
import kotlin.coroutines.experimental.buildSequence
fun generatePowers(m: Int) =
buildSequence {
var n = 0
val mm = m.toDouble()
while (true) yield(Math.pow((n++).toDouble(), mm).toLong())
}... |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #XLISP | XLISP | (defun greatest-common-divisor (x y)
(if (= y 0)
x
(greatest-common-divisor y (mod x y)) ) ) |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #XPL0 | XPL0 | include c:\cxpl\codes;
func GCD(U, V); \Return the greatest common divisor of U and V
int U, V;
int T;
[while V do \Euclid's method
[T:= U; U:= V; V:= rem(T/V)];
return abs(U);
];
\Display the GCD of two integers entered on command line
IntOut(0, GCD(IntIn(8), IntIn(8))) |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #PicoLisp | PicoLisp | (load "@lib/simul.l")
(seed (in "/dev/urandom" (rd 8)))
(loop
(match
'(@A B @B B @C)
(shuffle '(Q B B N N 0 0 0)) )
(NIL (bit? 1 (length @B))) )
(let Rkr '(R K R)
(for I (append @A '(B) @B '(B) @C)
(prin (if (=0 I) (pop 'Rkr) I)) )
(prinl) )
(bye) |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #PowerShell | PowerShell | function Get-RandomChess960Start
{
$Starts = @()
ForEach ( $Q in 0..3 ) {
ForEach ( $N1 in 0..4 ) {
ForEach ( $N2 in ($N1+1)..5 ) {
ForEach ( $B1 in 0..3 ) {
ForEach ( $B2 in 0..3 ) {
$BB = $B1 * 2 + ( $B1 -lt $B2 )
$BW = $B2 * 2
$Start = [... |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #Agda | Agda | compose : ∀ {a b c} {A : Set a} {B : Set b} {C : Set c}
→ (B → C)
→ (A → B)
→ A → C
compose f g x = f (g x) |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #Aikido | Aikido |
import math
function compose (f, g) {
return function (x) { return f(g(x)) }
}
var func = compose(Math.sin, Math.asin)
println (func(0.5)) // 0.5
|
http://rosettacode.org/wiki/FTP | FTP | Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
| #C.2B.2B | C++ | /* client.cpp
libftp++ C++ classes for ftplib C ftp library
compile:
clang++ -std=c++11 -o client client.cpp -lftp++
*/
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/stat.h> // stat
#include <ftplib.h> // libftp
#include <ftp++.hpp> // libftp+... |
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #JavaScript | JavaScript |
// A prototype declaration for a function that does not require arguments
function List() {}
List.prototype.push = function() {
return [].push.apply(this, arguments);
};
List.prototype.pop = function() {
return [].pop.call(this);
};
var l = new List();
l.push(5);
l.length; // 1
l[0]; 5
l.pop(); // 5
l.lengt... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #360_Assembly | 360 Assembly | DEFFUN CSECT
USING DEFFUN,R13
SAVEAREA B PROLOG-SAVEAREA(R15)
DC 17F'0'
PROLOG STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 set base register
BEGIN L R2,=F'13'
ST R2,X X=13
L ... |
http://rosettacode.org/wiki/French_Republican_calendar | French Republican calendar | Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of... | #FreeBASIC | FreeBASIC | ' version 18 Pluviose 227
' compile with: fbc -s console
' retained the original comments for then BBC BASIC entry
#Macro rep_leap (_year)
' see comment at the beginning of rep_to_day
((_year +1) Mod 4 = 0 And ((_year +1) Mod 100 <> 0 Or (_year +1) Mod 400 = 0))
#EndMacro
#Macro gre_leap (_year)
(_year ... |
http://rosettacode.org/wiki/Fusc_sequence | Fusc sequence |
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. Th... | #Arturo | Arturo | fusc: function [n][
if? or? n=0 n=1 -> n
else [
if? 0=n%2 -> fusc n/2
else -> (fusc (n-1)/2) + fusc (n+1)/2
]
]
print "The first 61 Fusc numbers:"
print map 0..61 => fusc
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
print " n fusc(n)"... |
http://rosettacode.org/wiki/Fusc_sequence | Fusc sequence |
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. Th... | #AutoHotkey | AutoHotkey | fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
while (StrLen(fusc[n]) < 5)
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
while (A_Index <= 61)
result .= (result = "" ? "" : ",") fusc[A_Index-1]
result .= "`n`nfusc number whose length is greater than any... |
http://rosettacode.org/wiki/Functional_coverage_tree | Functional coverage tree | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have... | #Phix | Phix | --
-- demo\rosetta\Functional_coverage_tree.exw
-- =========================================
--
with javascript_semantics
constant data = """
NAME_HIERARCHY | WEIGHT | COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms... |
http://rosettacode.org/wiki/Function_frequency | Function frequency | Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by... | #Factor | Factor | USING: accessors kernel math.statistics prettyprint sequences
sequences.deep source-files vocabs words ;
"resource:core/sequences/sequences.factor" "sequences"
[ path>source-file top-level-form>> ]
[ vocab-words [ def>> ] [ ] map-as ] bi* compose [ word? ]
deep-filter sorted-histogram <reversed> 7 head . |
http://rosettacode.org/wiki/Function_frequency | Function frequency | Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by... | #Forth | Forth | ' noop is bootmessage
\ --- LIST OF CONSTANTS
\ WORD# maximum word size
\ RING# size of `Rings' element
\ DEFS definitions
\ KEYS
\
\ --- LIST OF VARIABLES
\ cmpl? is compiling?
\ cword current compiled word
wordlist constant DEFS
wordlist constant KEYS
\ --- Compiling
50 constant WORD#
: >>fPAD ( ca... |
http://rosettacode.org/wiki/Gamma_function | Gamma function | Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma funct... | #BASIC256 | BASIC256 | print " x Stirling Lanczos"
print
for i = 1 to 20
d = i / 10.0
print d;
print chr(9); ljust(string(gammaStirling(d)), 13, "0");
print chr(9); ljust(string(gammaLanczos(d)), 13, "0")
next i
end
function gammaStirling (x)
e = exp(1) # e is not predefined in BASIC256
return sqr(2.... |
http://rosettacode.org/wiki/Galton_box_animation | Galton box animation | Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that ... | #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
const boxW = 41 // Galton box width
const boxH = 37 // Galton box height.
const pinsBaseW = 19 // Pins triangle base.
const nMaxBalls = 55 // Number of balls.
const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1
const (
empty = ' '
... |
http://rosettacode.org/wiki/Gapful_numbers | Gapful numbers | Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numb... | #FreeBASIC | FreeBASIC |
function is_gapful( n as uinteger ) as boolean
if n<100 then return false
dim as string ns = str(n)
dim as uinteger gap = 10*val(mid(ns,1,1)) + val(mid(ns,len(ns),1))
if n mod gap = 0 then return true else return false
end function
dim as ulongint i = 100
dim as ushort c
print "The first thirty gapf... |
http://rosettacode.org/wiki/Gaussian_elimination | Gaussian elimination | Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
| #Generic | Generic |
generic coordinaat
{
ecs;
uuii;
coordinaat() { ecs=+a;uuii=+a;}
coordinaat(ecs_set,uuii_set) { ecs = ecs_set; uuii=uuii_set;}
operaator<(c)
{
iph ecs < c.ecs return troo;
iph c.ecs < ecs return phals;
iph uuii < c.uuii return troo;
return phals;
}
operaator==(connpair) // eecuuols and not ... |
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion | Gauss-Jordan matrix inversion | Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
| #Lambdatalk | Lambdatalk |
{require lib_matrix}
{M.gaussJordan
{M.new [[1,2,3],
[4,5,6],
[7,8,-9]]}}
->
[[-1.722222222222222,0.7777777777777777,-0.05555555555555555],
[1.4444444444444444,-0.5555555555555556,0.1111111111111111],
[-0.05555555555555555,0.1111111111111111,-0.05555555555555555]]
|
http://rosettacode.org/wiki/General_FizzBuzz | General FizzBuzz | Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ... | #JavaScript | JavaScript | function fizz(d, e) {
return function b(a) {
return a ? b(a - 1).concat(a) : [];
}(e).reduce(function (b, a) {
return b + (d.reduce(function (b, c) {
return b + (a % c[0] ? "" : c[1]);
}, "") || a.toString()) + "\n";
}, "");
} |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #zkl | zkl | fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z);
if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,z)) } |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #DUP | DUP | 0"abcdefghijklmnopqrstuvwxyz" {store character values of string in cells 0..length of string-1}
26[$][^^-;,1-]# {Loop from 26-26 to 26-0, print the respective cell contents to STDOUT} |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #Dyalect | Dyalect | print << ('a'..'z').ToArray() |
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
| #Onyx | Onyx | `Hello world!\n' print flush |
http://rosettacode.org/wiki/Generator/Exponential | Generator/Exponential | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the objec... | #Lingo | Lingo | squares = script("generator.power").new(2)
cubes = script("generator.power").new(3)
filter = script("generator.filter").new(squares, cubes)
filter.skip(20)
res = []
i = 0
repeat while filter.exec(res)
i = i + 1
if i>10 then exit repeat
put res[1]
end repeat |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Yabasic | Yabasic | sub gcd(u, v)
local t
u = int(abs(u))
v = int(abs(v))
while(v)
t = u
u = v
v = mod(t, v)
wend
return u
end sub
print "Greatest common divisor: ", gcd(12345, 9876) |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Z80_Assembly | Z80 Assembly | ; Inputs: a, b
; Outputs: a = gcd(a, b)
; Destroys: c
; Assumes: a and b are positive one-byte integers
gcd:
cp b
ret z ; while a != b
jr c, else ; if a > b
sub b ; a = a - b
jr gcd
else:
ld c, a ; Save a
ld a, b ... |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #Python | Python | >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2 # Bishop constraint
and ( p.index('r') < p.index('K') < p.index('R') # King constraint
... |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #Aime | Aime | compose_i(,,)
{
($0)(($1)($2));
}
compose(,)
{
compose_i.apply($0, $1);
}
double(real a)
{
2 * a;
}
square(real a)
{
a * a;
}
main(void)
{
o_(compose(square, double)(40), "\n");
0;
} |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #ALGOL_68 | ALGOL 68 | MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
# As a procedure for real to real functions #
PROC compose = (F f, g)F: (REAL x)REAL: f(g(x));
OP (F,F)F O = compose; # or an OPerator that can be overloaded #
# Example use: #
F sin arc sin = compose(sin, arc sin);
print((sin arc sin(0.5), (sin O arc sin)(0.5... |
http://rosettacode.org/wiki/FTP | FTP | Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
| #Common_Lisp | Common Lisp | (use-package :ftp)
(with-ftp-connection (conn :hostname "ftp.hq.nasa.gov"
:passive-ftp-p t)
(send-cwd-command conn "/pub/issoutreach/Living in Space Stories (MP3 Files)")
(send-list-command conn t)
(let ((filename "Gravity in the Brain.mp3"))
(retrieve-file conn filename filename... |
http://rosettacode.org/wiki/FTP | FTP | Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
| #Erlang | Erlang |
%%%-------------------------------------------------------------------
%%% To execute in shell, Run the following commands:-
%%% >c("ftp_example").
%%% >ftp_example:run().
%%%-------------------------------------------------------------------
-module(ftp_example).
-export([run/0]).
run() ->
Host = "ftp.easyne... |
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #Julia | Julia | julia > function mycompare(a, b)::Cint
(a < b) ? -1 : ((a > b) ? +1 : 0)
end
mycompare (generic function with 1 method)
|
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #Kotlin | Kotlin | // version 1.0.6
interface MyInterface {
fun foo() // no arguments, no return type
fun goo(i: Int, j: Int) // two arguments, no return type
fun voo(vararg v: Int) // variable number of arguments, no return type
fun ooo(o: Int = 1): Int // optional argument with de... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #6502_Assembly | 6502 Assembly | MULTIPLY: STX MULN ; 6502 has no "acc += xreg" instruction,
TXA ; so use a memory address
MULLOOP: DEY
CLC ; remember to clear the carry flag before
ADC MULN ; doing addition or subtraction
CPY #$01
BNE MULLOOP
RTS |
http://rosettacode.org/wiki/French_Republican_calendar | French Republican calendar | Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of... | #F.23 | F# |
// French Republican Calander: Nigel Galloway. April 16th., 2021
let firstDay=System.DateTime.Parse("22/9/1792")
type monthsFRC= Vendemiaire = 0
|Brumaire = 30
|Frimaire = 60
|Nivose = 90
|Pluviose = 120
|Ventose = 150
... |
http://rosettacode.org/wiki/Fusc_sequence | Fusc sequence |
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. Th... | #AWK | AWK |
# syntax: GAWK -f FUSC_SEQUENCE.AWK
# converted from C
BEGIN {
for (i=0; i<61; i++) {
printf("%d ",fusc(i))
}
printf("\n")
print("fusc numbers whose length is greater than any previous fusc number length")
printf("%9s %9s\n","fusc","index")
for (i=0; i<=700000; i++) {
f = fusc(i)
... |
http://rosettacode.org/wiki/Functional_coverage_tree | Functional coverage tree | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have... | #Python | Python | from itertools import zip_longest
fc2 = '''\
cleaning,,
house1,40,
bedrooms,,.25
bathrooms,,
bathroom1,,.5
bathroom2,,
outside_lavatory,,1
attic,,.75
kitchen,,.1
living_rooms,,
lounge,,
dining_room,,
... |
http://rosettacode.org/wiki/Function_frequency | Function frequency | Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by... | #Go | Go | package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"sort"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("usage ff <go source filename>")
return
}
src, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println(err... |
http://rosettacode.org/wiki/Gamma_function | Gamma function | Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma funct... | #BBC_BASIC | BBC BASIC | *FLOAT64
INSTALL @lib$+"FNUSING"
FOR x = 0.1 TO 2.05 STEP 0.1
PRINT FNusing("#.#",x), FNusing("##.############", FNgamma(x))
NEXT
END
DEF FNgamma(z) = EXP(FNlngamma(z))
DEF FNlngamma(z)
LOCAL a, b, i%, lz()
DIM lz(6)
lz() = 1.000000000190015, 76.... |
http://rosettacode.org/wiki/Galton_box_animation | Galton box animation | Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that ... | #Haskell | Haskell | import Data.Map hiding (map, filter)
import Graphics.Gloss
import Control.Monad.Random
data Ball = Ball { position :: (Int, Int), turns :: [Int] }
type World = ( Int -- number of rows of pins
, [Ball] -- sequence of balls
, Map Int Int ) -- counting bins
updateWorld :: W... |
http://rosettacode.org/wiki/Gapful_numbers | Gapful numbers | Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numb... | #Frink | Frink |
// Create function to calculate gapful number
gapful[num,totalCounter] :=
{
// Display a line explaining the current calculation.
println["First $totalCounter gapful numbers over $num:"]
// Start a counter to compare with the total count.
counter = 0
while counter < totalCounter
{
numStr = toS... |
http://rosettacode.org/wiki/Gapful_numbers | Gapful numbers | Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numb... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
starts := []uint64{1e2, 1e6, 1e7, 1e9, 7123}
counts := []int{30, 15, 15, 10, 25}
for i :=... |
http://rosettacode.org/wiki/Gaussian_elimination | Gaussian elimination | Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
| #Go | Go | package main
import (
"errors"
"fmt"
"log"
"math"
)
type testCase struct {
a [][]float64
b []float64
x []float64
}
var tc = testCase{
// common RC example. Result x computed with rational arithmetic then
// converted to float64, and so should be about as close to correct as
... |
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion | Gauss-Jordan matrix inversion | Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a = N@{{1, 7, 5, 0}, {5, 8, 6, 9}, {2, 1, 6, 4}, {8, 1, 2, 4}};
elimmat = RowReduce[Join[a, IdentityMatrix[Length[a]], 2]];
inv = elimmat[[All, -Length[a] ;;]] |
http://rosettacode.org/wiki/General_FizzBuzz | General FizzBuzz | Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ... | #Julia | Julia | function fizzbuzz(triggers :: Vector{Tuple{Int, ASCIIString}}, upper :: Int)
for i = 1 : upper
triggered = false
for trigger in triggers
if i % trigger[1] == 0
triggered = true
print(trigger[2])
end
end
!triggered && print(i... |
http://rosettacode.org/wiki/General_FizzBuzz | General FizzBuzz | Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ... | #Kotlin | Kotlin | fun main(args: Array<String>) {
//Read the maximum number, set to 0 if it couldn't be read
val max = readLine()?.toInt() ?: 0
val words = mutableMapOf<Int, String>()
//Read input three times for a factor and a word
(1..3).forEach {
readLine()?.let {
val tokens = it.split(' ')... |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET n=27: LET s=1
20 GO SUB 1000
30 PRINT '"Sequence length = ";seqlen
40 LET maxlen=0: LET s=0
50 FOR m=2 TO 100000
60 LET n=m
70 GO SUB 1000
80 IF seqlen>maxlen THEN LET maxlen=seqlen: LET maxnum=m
90 NEXT m
100 PRINT "The number with the longest hailstone sequence is ";maxnum
110 PRINT "Its sequence length is ";m... |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #EchoLisp | EchoLisp |
;; 1)
(define \a (first (string->unicode "a")))
(for/list ((i 25)) (unicode->string (+ i \a)))
→ (a b c d e f g h i j k l m n o p q r s t u v w x y)
;;2) using a sequence
(lib 'sequences)
(take ["a" .. "z"] 26)
→ (a b c d e f g h i j k l m n o p q r s t u v w x y z)
; or
(for/string ((letter ["a" .. "z"... |
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
| #OOC | OOC | main: func {
"Hello world!" println()
} |
http://rosettacode.org/wiki/Generator/Exponential | Generator/Exponential | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the objec... | #Lua | Lua |
--could be done with a coroutine, but a simple closure works just as well.
local function powgen(m)
local count = 0
return function()
count = count + 1
return count^m
end
end
local squares = powgen(2)
local cubes = powgen(3)
local cowrap,coyield = coroutine.wrap, coroutine.yield
local function fil... |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #zkl | zkl | (123456789).gcd(987654321) //-->9 |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR n=1 TO 3
20 READ a,b
30 PRINT "GCD of ";a;" and ";b;" = ";
40 GO SUB 70
50 NEXT n
60 STOP
70 IF b=0 THEN PRINT ABS (a): RETURN
80 LET c=a: LET a=b: LET b=FN m(c,b): GO TO 70
90 DEF FN m(a,b)=a-INT (a/b)*b
100 DATA 12,16,22,33,45,67 |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #R | R |
pieces <- c("R","B","N","Q","K","N","B","R")
generateFirstRank <- function() {
attempt <- paste0(sample(pieces), collapse = "")
while (!check_position(attempt)) {
attempt <- paste0(sample(pieces), collapse = "")
}
return(attempt)
}
check_position <- function(position) {
if (regexpr('.*R.*K.*R.*', po... |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #AntLang | AntLang | /Apply g to exactly one argument
compose1: {f: x; g: y; {f[g[x]]}}
/Extra: apply to multiple arguments
compose: {f: x; g: y; {f[g apply args]}} |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #AppleScript | AppleScript | -- Compose two functions where each function is
-- a script object with a call(x) handler.
on compose(f, g)
script
on call(x)
f's call(g's call(x))
end call
end script
end compose
script sqrt
on call(x)
x ^ 0.5
end call
end script
script twice
on call(x)
... |
http://rosettacode.org/wiki/Fractran | Fractran | FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
... | #11l | 11l | F fractran(prog, =val, limit)
V fracts = prog.split(‘ ’).map(p -> p.split(‘/’).map(i -> Int(i)))
[Float] r
L(n) 0 .< limit
r [+]= val
L(p) fracts
I val % p[1] == 0
val = p[0] * val / p[1]
L.break
R r
print(fractran(‘17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/... |
http://rosettacode.org/wiki/FTP | FTP | Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
| #Go | Go | package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
// Hard-coded demonstration values
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != n... |
http://rosettacode.org/wiki/FTP | FTP | Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
| #Groovy | Groovy |
@Grab(group='commons-net', module='commons-net', version='2.0')
import org.apache.commons.net.ftp.FTPClient
println("About to connect....");
new FTPClient().with {
connect "ftp.easynet.fr"
enterLocalPassiveMode()
login "anonymous", "ftptest@example.com"
changeWorkingDirectory "/debian/"
def inco... |
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #Lua | Lua | function Func() -- Does not require arguments
return 1
end
function Func(a,b) -- Requires arguments
return a + b
end
function Func(a,b) -- Arguments are optional
return a or 4 + b or 2
end
function Func(a,...) -- One argument followed by varargs
return a,{...} -- Returns both arguments, varargs as table
end |
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #Luck | Luck | function noargs(): int = ? ;;
function twoargs(x:int, y:int): int = ? ;;
/* underscore means ignore and is not bound to lexical scope */
function twoargs(_:bool, _:bool): int = ? ;;
function anyargs(xs: ...): int = ? ;;
function plusargs(x:int, xs: ...): int = ? ;; |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #68000_Assembly | 68000 Assembly | MOVE.L D0,#$0200
MOVE.L D1,#$0400
JSR doMultiply
;rest of program
JMP $ ;halt
;;;;; somewhere far away from the code above
doMultiply:
MULU D0,D1
RTS
|
http://rosettacode.org/wiki/French_Republican_calendar | French Republican calendar | Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of... | #Go | Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var (
gregorianStr = []string{"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"}
gregorian = []int{31, 28, 31, 30, 31, 30, 31,... |
http://rosettacode.org/wiki/Fusc_sequence | Fusc sequence |
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. Th... | #BASIC256 | BASIC256 | global f, max
max = 36000
dim f(max)
call fusc()
for i = 0 to 60
print f[i]; " ";
next i
print : print
print " Index Value"
d = 0
for i = 0 to max-1
if f[i] >= d then
print rjust(string(i),10," "), rjust(string(f[i]),10," ")
if d = 0 then d = 1
d *= 10
end if
next i
end
subroutine fus... |
http://rosettacode.org/wiki/Fusc_sequence | Fusc sequence |
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. Th... | #BQN | BQN | Fusc ← {
{
𝕩∾+´(⍷(⌈∾⌊)2÷˜≠𝕩)⊑¨<𝕩
}⍟(𝕩-2)↕2
}
•Show Fusc 61
•Show >⟨"Index"‿"Number"⟩∾{((1+↕4)⊐˜(⌊1+10⋆⁼1⌈|)¨𝕩){𝕨∾𝕨⊑𝕩}¨<𝕩} Fusc 99999 |
http://rosettacode.org/wiki/Functional_coverage_tree | Functional coverage tree | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have... | #Racket | Racket | #lang racket/base
(require racket/list racket/string racket/match racket/format racket/file)
(struct Coverage (name weight coverage weighted-coverage children) #:transparent #:mutable)
;; -| read/parse |------------------------------------------------------------------------------------
(define (build-hierarchies p... |
http://rosettacode.org/wiki/Functional_coverage_tree | Functional coverage tree | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have... | #Raku | Raku | sub walktree ($data) {
my (@parts, $cnt);
while ($data ~~ m:nth(++$cnt)/$<head>=[(\s*) \N+\n ] # split off one level as 'head' (or terminal 'leaf')
$<body>=[[$0 \s+ \N+\n]*]/ ) { # next sub-level is 'body' (defined by extra depth of indentation)
my ($head,... |
http://rosettacode.org/wiki/Function_frequency | Function frequency | Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by... | #Haskell | Haskell | import Language.Haskell.Parser (parseModule)
import Data.List.Split (splitOn)
import Data.List (nub, sortOn, elemIndices)
findApps src = freq $ concat [apps, comps]
where
ast = show $ parseModule src
apps = extract <$> splitApp ast
comps = extract <$> concat (splitComp <$> splitInfix ast)
splitApp =... |
http://rosettacode.org/wiki/Function_frequency | Function frequency | Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by... | #J | J |
IGNORE=: ;:'y(0)1',CR
Filter=: (#~`)(`:6)
NB. extract tokens from a large body newline terminated of text
roughparse=: ;@(<@;: ::(''"_);._2)
NB. count frequencies and get the top x
top=: top=: {. \:~@:((#;{.)/.~)
NB. read all installed script (.ijs) files and concatenate them
JSOURCE=:... |
http://rosettacode.org/wiki/Gamma_function | Gamma function | Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma funct... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
/* very simple approximation */
double st_gamma(double x)
{
return sqrt(2.0*M_PI/x)*pow(x/M_E, x);
}
#define A 12
double sp_gamma(double z)
{
const int a = A;
static d... |
http://rosettacode.org/wiki/Galton_box_animation | Galton box animation | Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that ... | #Icon_and_Unicon | Icon and Unicon | link graphics
global pegsize, pegsize2, height, width, delay
procedure main(args) # galton box simulation from Unicon book
pegsize2 := (pegsize := 10) * 2 # pegs & steps
delay := 2 # ms delay
setup_galtonwindow(pegsize)
n := integer(args[1]) | 100 # balls to drop
... |
http://rosettacode.org/wiki/Gapful_numbers | Gapful numbers | Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numb... | #Go | Go | package main
import "fmt"
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
starts := []uint64{1e2, 1e6, 1e7, 1e9, 7123}
counts := []int{30, 15, 15, 10, 25}
for i :=... |
http://rosettacode.org/wiki/Gaussian_elimination | Gaussian elimination | Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
| #Haskell | Haskell |
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss
gauss::[[Double]] -> [[Do... |
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion | Gauss-Jordan matrix inversion | Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
| #MATLAB | MATLAB | function GaussInverse(M)
original = M;
[n,~] = size(M);
I = eye(n);
for j = 1:n
for i = j:n
if ~(M(i,j) == 0)
for k = 1:n
q = M(j,k); M(j,k) = M(i,k); M(i,k) = q;
q = I(j,k); I(j,k) = I(i,k); I(i,k) = q;
end
... |
http://rosettacode.org/wiki/General_FizzBuzz | General FizzBuzz | Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ... | #LiveCode | LiveCode | function generalisedFizzBuzz m, f1, f2, f3
put f1 & cr & f2 & cr & f3 into factors
sort factors ascending numeric
repeat with i = 1 to m
put false into flag
if i mod (word 1 of line 1 of factors) = 0 then
put word 2 of line 1 of factors after fizzbuzz
put true into fl... |
http://rosettacode.org/wiki/General_FizzBuzz | General FizzBuzz | Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ... | #Lua | Lua | function genFizz (param)
local response
print("\n")
for n = 1, param.limit do
response = ""
for i = 1, 3 do
if n % param.factor[i] == 0 then
response = response .. param.word[i]
end
end
if response == "" then print(n) else print(response) end
end
end
local param = {factor =... |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #Elena | Elena | import extensions;
import system'collections;
singleton Alphabet : Enumerable
{
Enumerator enumerator() = new Enumerator
{
char current;
get() = current;
bool next()
{
if (nil==current)
{
current := $97
}
else ... |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #Elixir | Elixir | iex(1)> Enum.to_list(?a .. ?z)
'abcdefghijklmnopqrstuvwxyz'
iex(2)> Enum.to_list(?a .. ?z) |> List.to_string
"abcdefghijklmnopqrstuvwxyz" |
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
| #ooRexx | ooRexx | /* Rexx */
say 'Hello world!'
|
http://rosettacode.org/wiki/Generator/Exponential | Generator/Exponential | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the objec... | #M2000_Interpreter | M2000 Interpreter |
Module Generator {
PowGen = Lambda (e)-> {
=lambda i=0, e -> {
i++
=i**e
}
}
Squares=lambda PowGen=PowGen(2) ->{
=PowGen()
}
Cubes=Lambda PowGen=PowGen(3) -> {
=PowGen()
}
Fi... |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #Racket | Racket | #lang racket
(define white (match-lambda ['P #\♙] ['R #\♖] ['B #\♗] ['N #\♘] ['Q #\♕] ['K #\♔]))
(define black (match-lambda ['P #\♟] ['R #\♜] ['B #\♝] ['N #\♞] ['Q #\♛] ['K #\♚]))
(define (piece->unicode piece colour)
(match colour ('w white) ('b black)) piece)
(define (find/set!-random-slot vec val k (f values)... |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #Raku | Raku | repeat until m/ '♗' [..]* '♗' / { $_ = < ♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘ >.pick(*).join }
s:2nd['♖'] = '♔';
say .comb; |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #Applesoft_BASIC | Applesoft BASIC | 10 F$ = "SIN"
20 DEF FN A(P) = ATN(P/SQR(-P*P+1))
30 G$ = "FN A"
40 GOSUB 100"COMPOSE
50 SA$ = E$
60 X = .5 : E$ = SA$
70 GOSUB 200"EXEC
80 PRINT R
90 END
100 E$ = F$ + "(" + G$ + "(X))" : RETURN : REMCOMPOSE F$ G$
200 D$ = CHR$(4) : FI$ = "TEMPORARY.EX" : M$ = CHR$(13)
210 PRINT D$"OPEN"FI$M$D$"CLOSE"FI$M$D$"DEL... |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #Argile | Argile | use std, math
let my_asin = new Function (.:<any,real x>:. -> real {asin x})
let my__sin = new Function (.:<any,real x>:. -> real { sin x})
let sinasin = my__sin o my_asin
print sin asin 0.5
print *my__sin 0.0
print *sinasin 0.5
~my_asin
~my__sin
~sinasin
=: <Function f> o <Function g> := -> Function {compose f g}
... |
http://rosettacode.org/wiki/Fractran | Fractran | FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
... | #360_Assembly | 360 Assembly | * FRACTRAN 17/02/2019
FRACTRAN CSECT
USING FRACTRAN,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST... |
http://rosettacode.org/wiki/FTP | FTP | Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
| #Haskell | Haskell | module Main (main) where
import Control.Exception (bracket)
import Control.Monad (void)
import Data.Foldable (for_)
import Network.FTP.Client
( cwd
, easyConnectFTP
, getbinary
, loginAnon
... |
http://rosettacode.org/wiki/FTP | FTP | Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
| #J | J | require 'web/gethttp'
gethttp 'ftp://anonymous:example@ftp.hq.nasa.gov/pub/issoutreach/Living%20in%20Space%20Stories%20(MP3%20Files)/'
-rw-rw-r-- 1 109 space-station 2327118 May 9 2005 09sept_spacepropulsion.mp3
-rw-rw-r-- 1 109 space-station 1260304 May 9 2005 Can People go to Mars.mp3
-rw-rw... |
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #M2000_Interpreter | M2000 Interpreter |
Module Check {
Module MyBeta (a) {
Print "MyBeta", a/2
}
Module TestMe {
Module Beta (x) {
Print "TestMeBeta", x
}
Beta 100
}
TestMe ; Beta as MyBeta
}
Check
|
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #Nim | Nim | # Procedure declarations. All are named
proc noargs(): int
proc twoargs(a, b: int): int
proc anyargs(x: varargs[int]): int
proc optargs(a, b: int = 10): int
# Usage
discard noargs()
discard twoargs(1,2)
discard anyargs(1,2,3,4,5,6,7,8)
discard optargs(5)
# Procedure definitions
proc noargs(): int = echo "noargs"
pr... |
http://rosettacode.org/wiki/Function_prototype | Function prototype | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A p... | #OCaml | OCaml | (* Usually prototype declarations are put in an interface file,
a file with .mli filename extension *)
(* A prototype declaration for a function that does not require arguments *)
val no_arg : unit -> unit
(* A prototype declaration for a function that requires two arguments *)
val two_args : int -> int -> unit
... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #8051_Assembly | 8051 Assembly | ORG RESET
mov a, #100
mov b, #10
call multiply
; at this point, the result of 100*10 = 1000 = 03e8h is stored in registers a and b
; a = e8
; b = 03
jmp $
multiply:
mul ab
ret |
http://rosettacode.org/wiki/French_Republican_calendar | French Republican calendar | Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of... | #Julia | Julia | using Dates
const GC_FORMAT = DateFormat("d U y")
const RC_FIRST_DAY = Date(1792, 9, 22)
const MAX_RC_DATE = Date(1805, 12, 31)
const RC_MONTHS = [
"Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse",
"Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor"
]
const RC... |
http://rosettacode.org/wiki/French_Republican_calendar | French Republican calendar | Write a program to convert dates between the Gregorian calendar and the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of... | #Kotlin | Kotlin | // version 1.1.4-3
import java.time.format.DateTimeFormatter
import java.time.LocalDate
import java.time.temporal.ChronoUnit.DAYS
/* year = 1.. month = 1..13 day = 1..30 */
class FrenchRCDate(val year: Int, val month: Int, val day: Int) {
init {
require (year > 0 && month in 1..13)
if (mont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.