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/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... | #Visual_Basic_.NET | Visual Basic .NET | Module HailstoneSequence
Sub Main()
' Checking sequence of 27.
Dim l As List(Of Long) = HailstoneSequence(27)
Console.WriteLine("27 has {0} elements in sequence:", l.Count())
For i As Integer = 0 To 3 : Console.Write("{0}, ", l(i)) : Next
Console.Write("... ")
For... |
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... | #CLU | CLU | alph = proc () returns (string)
a: int := char$c2i('a')
letters: array[char] := array[char]$predict(1,26)
for i: int in int$from_to(0, 25) do
array[char]$addh(letters, char$i2c(a + i))
end
return(string$ac2s(letters))
end alph
% test
start_up = proc ()
stream$putl(stream$primary_output... |
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... | #COBOL | COBOL | identification division.
program-id. lower-case-alphabet-program.
data division.
working-storage section.
01 ascii-lower-case.
05 lower-case-alphabet pic a(26).
05 character-code pic 999.
05 loop-counter pic 99.
procedure division.
control-paragraph.
perform add-next-letter-paragraph varyin... |
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
| #Occam | Occam | #USE "course.lib"
PROC main (CHAN BYTE screen!)
out.string("Hello world!*c*n", 0, screen)
: |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #XBS | XBS | set x=1;
set y=2;
log("Before Swap");
log(x);
log(y);
swap x y;
log("After Swap");
log(x);
log(y); |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #XPL0 | XPL0 | include c:\cxpl\codes;
proc Exch(A, B, S);
char A, B, S;
int I, T;
for I:= 0 to S-1 do
[T:= A(I); A(I):= B(I); B(I):= T];
real X, Y;
[X:= 3.0; Y:= 4.0;
Exch(addr X, addr Y, 8);
RlOut(0, X); RlOut(0, Y); CrLf(0);
] |
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... | #Java | Java | import java.util.function.LongSupplier;
import static java.util.stream.LongStream.generate;
public class GeneratorExponential implements LongSupplier {
private LongSupplier source, filter;
private long s, f;
public GeneratorExponential(LongSupplier source, LongSupplier filter) {
this.source = so... |
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... | #VBScript | VBScript | Function GCD(a,b)
Do
If a Mod b > 0 Then
c = a Mod b
a = b
b = c
Else
GCD = b
Exit Do
End If
Loop
End Function
WScript.Echo "The GCD of 48 and 18 is " & GCD(48,18) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(1280,240) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(3475689,235... |
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... | #Verilog | Verilog | module gcd
(
input reset_l,
input clk,
input [31:0] initial_u,
input [31:0] initial_v,
input load,
output reg [31:0] result,
output reg busy
);
reg [31:0] u, v;
always @(posedge clk or negedge reset_l)
if (!reset_l)
begin
busy <= 0;
u <= 0;
v <= 0;
end
else
be... |
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... | #Nim | Nim | import random, strutils
type
# Chess pieces on first row.
Pieces {.pure.} = enum
King = "♔",
Queen = "♕",
Rook1 = "♖",
Rook2 = "♖",
Bishop1 = "♗",
Bishop2 = "♗",
Knight1 = "♘",
Knight2 = "♘"
# Position counted from 0.
Position = range[0..7]
# Position of pieces.
Posit... |
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... | #Objeck | Objeck | class Chess960 {
function : Main(args : String[]) ~ Nil {
Generate(10);
}
function : Generate(c : Int) ~ Nil {
for(x := 0; x < c; x += 1;) {
StartPos()->PrintLine();
};
}
function : StartPos() ~ String {
p := Char->New[8];
# bishops
b1 : Int; b2 : Int;
while(true) {
... |
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... | #Delphi | Delphi |
program Function_prototype;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TIntArray = TArray<Integer>;
TIntArrayHelper = record helper for TIntArray
const
DEFAULT_VALUE = -1;
// A prototype declaration for a function that does not require arguments
function ToString(): string;
//... |
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... | #11l | 11l | F fusc(n)
V res = [0] * n
res[1] = 1
L(i) 2 .< n
res[i] = I i % 2 == 0 {res[i I/ 2]} E res[(i-1) I/ 2] + res[(i+1) I/ 2]
R res
print(‘First 61 terms:’)
print(fusc(61))
print()
print(‘Points in the sequence where an item has more digits than any previous items:’)
V f = fusc(20'000'000)
V max_len = ... |
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... | #J | J | raw=: 0 :0
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | ... |
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... | #JavaScript | JavaScript | (() => {
'use strict';
// updatedCoverageOutline :: String -> String
const updatedCoverageOutline = outlineText => {
const
delimiter = '|',
indentedLines = indentLevelsFromLines(lines(outlineText)),
columns = init(tokenizeWith(delimiter)(snd(indentedLines[0])));... |
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... | #Arturo | Arturo | source: to :block read arg\0
frequencies: #[]
inspectBlock: function [blk][
loop blk 'item [
case []
when? [word? item][
sItem: to :string item
if set? sItem ->
if function? var sItem [
if? key? frequencies sItem ->
... |
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... | #AWK | AWK |
# syntax: GAWK -f FUNCTION_FREQUENCY.AWK filename(s).AWK
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
# create array of keywords to be ignored by lexer
asplit("BEGIN:END:atan2:break:close:continue:cos:delete:" \
"do:else:exit:exp:fo... |
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... | #ANSI_Standard_BASIC | ANSI Standard BASIC | 100 DECLARE EXTERNAL FUNCTION FNlngamma
110
120 DEF FNgamma(z) = EXP(FNlngamma(z))
130
140 FOR x = 0.1 TO 2.05 STEP 0.1
150 PRINT USING$("#.#",x), USING$("##.############", FNgamma(x))
160 NEXT x
170 END
180
190 EXTERNAL FUNCTION FNlngamma(z)
200 DIM lz(0 TO 6)
210 RESTORE
220 MAT READ lz
230 DATA 1.0000000001900... |
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 ... | #C.2B.2B | C++ |
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObj... |
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... | #D | D | import std.conv;
import std.stdio;
string commatize(ulong n) {
auto s = n.to!string;
auto le = s.length;
for (int i = le - 3; i >= 1; i -= 3) {
s = s[0..i]
~ ","
~ s[i..$];
}
return s;
}
void main() {
ulong[] starts = [cast(ulong)1e2, cast(ulong)1e6, cast(ulong)1e... |
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
| #Delphi | Delphi | program GuassianElimination;
// Modified from:
// R. Sureshkumar (10 January 1997)
// Gregory J. McRae (22 October 1997)
// http://web.mit.edu/10.001/Web/Course_Notes/Gauss_Pivoting.c
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TMatrix = class
private
_r, _c : integer;
data ... |
http://rosettacode.org/wiki/Generate_random_chess_position | Generate random chess position | Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any p... | #Typescript | Typescript |
class Fen {
public createFen() {
let grid: string[][];
grid = [];
for (let r = 0; r < 8; r++) {
grid[r] = [];
for (let c = 0; c < 8; c++) {
grid[r][c] = "0";
}
}
this.placeKings(grid);
this.placePieces(grid... |
http://rosettacode.org/wiki/Generate_random_chess_position | Generate random chess position | Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any p... | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var grid = List.filled(8, null)
for (i in 0..7) grid[i] = List.filled(9, ".")
var placeKings = Fn.new {
while (true) {
var r1 = rand.int(8)
var c1 = rand.int(8)
var r2 = rand.int(8)
var c2 = rand.int(8)
... |
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.
| #Java | Java | // GaussJordan.java
import java.util.Random;
public class GaussJordan {
public static void main(String[] args) {
int rows = 5;
Matrix m = new Matrix(rows, rows);
Random r = new Random();
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < rows; ++colu... |
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 ... | #Go | Go |
package main
import (
"fmt"
)
const numbers = 3
func main() {
//using the provided data
max := 20
words := map[int]string{
3: "Fizz",
5: "Buzz",
7: "Baxx",
}
keys := []int{3, 5, 7}
divisible := false
for i := 1; i <= max; i++ {
for _, n := range keys {
if i % n == 0 {
fmt.Print(words[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... | #Vlang | Vlang | // 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
fn hs(nn int, recycle []int) []int {
mut n := nn
mut s := recycle[..0]
s << n
for n > 1 {
if n&1 == 0 {
n /= 2
} else {
n = 3*n + 1
}
s << n... |
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... | #CoffeeScript | CoffeeScript |
(String.fromCharCode(x) for x in [97..122])
|
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... | #Comal | Comal | dim alphabet$ of 26
for i := 1 to 26
alphabet$(i) := chr$(ord("a") - 1 + i)
endfor i
print alphabet$ |
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
| #Octave | Octave | disp("Hello world!"); |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Yabasic | Yabasic | a = 1
b = 2
print a, b
//----- swap ----
temp = a : a = b : b = temp
print a, b |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Yorick | Yorick | > a = 1
> b = "foo"
> swap, a, b
> a
"foo"
> b
1 |
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... | #JavaScript | JavaScript |
function PowersGenerator(m) {
var n=0;
while(1) {
yield Math.pow(n, m);
n += 1;
}
}
function FilteredGenerator(g, f){
var value = g.next();
var filter = f.next();
while(1) {
if( value < filter ) {
yield value;
value = g.next();
} else if ( value > filter ) {
filter = f.next();
} else {
... |
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... | #Visual_Basic | Visual Basic | Function GCD(ByVal a As Long, ByVal b As Long) As Long
Dim h As Long
If a Then
If b Then
Do
h = a Mod b
a = b
b = h
Loop While b
End If
GCD = Abs(a)
Else
GCD = Abs(b)
End If
End Function
Sub Main()
... |
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... | #Vlang | Vlang | fn gcd(xx int, yy int) int {
mut x, mut y := xx, yy
for y != 0 {
x, y = y, x%y
}
return x
}
fn main() {
println(gcd(33, 77))
println(gcd(49865, 69811))
}
|
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... | #PARI.2FGP | PARI/GP | chess960() =
{
my (C = vector(8), i, j, r);
C[random(4) * 2 + 1] = C[random(4) * 2 + 2] = "B";
for (i = 1, 3, while (C[r = random(8) + 1],); C[r] = Vec("NNQ")[i]);
for (i = 1, 8, if (!C[i], C[i] = Vec("RKR")[j++]));
C
} |
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... | #Diego | Diego | // A prototype declaration for a function that does not require arguments
begin_funct(foo); // function as a 'method' with no arguments, no return type
end_funct(foo);
// or
with_funct(foo); // function as a 'method' with no arguments, no return type
// A pro... |
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... | #F.23 | F# | // A function taking and returning nothing (unit).
val noArgs : unit -> unit
// A function taking two integers, and returning an integer.
val twoArgs : int -> int -> int
// A function taking a ParamPack array of ints, and returning an int. The ParamPack
// attribute is not included in the signature.
val varArgs : int [... |
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... | #Ada | Ada | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
... |
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... | #Julia | Julia | using CSV, DataFrames, Formatting
function updatecoverage(dfname, outputname)
df = CSV.read(dfname)
dchild = Dict{Int, Vector{Int}}([i => Int[] for i in 0:maximum(df[!, 1])])
for row in eachrow(df)
push!(dchild[row[3]], row[1])
end
function coverage(t)
return dchild[t] == [] ? ... |
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... | #Kotlin | Kotlin | // version 1.2.10
class FCNode(val name: String, val weight: Int = 1, coverage: Double = 0.0) {
var coverage = coverage
set(value) {
if (field != value) {
field = value
// update any parent's coverage
if (parent != null) parent!!.updateCoverage()
... |
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... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(1,0) : REM Descending
Valid$ = "0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz"
DIM func$(1000), cnt%(1000)
nFunc% = 0
file% = OPENIN("*.bbc")
WHILE NOT EOF#file%
ll% = BGET#file%
no% = BGET#file... |
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... | #C | C |
#define _POSIX_SOURCE
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stddef.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct functionInfo {
char* name;
int timesCalled;
char marked;
};
void addToLis... |
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... | #Arturo | Arturo | A: @[
1.00000000000000000000 0.57721566490153286061 neg 0.65587807152025388108
neg 0.04200263503409523553 0.16653861138229148950 neg 0.04219773455554433675
neg 0.00962197152787697356 0.00721894324666309954 neg 0.00116516759185906511
neg 0.00021524167411495097 0.00012805028238811619 neg 0.00002013485... |
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 ... | #D | D | import std.stdio, std.algorithm, std.random, std.array;
enum int boxW = 41, boxH = 37; // Galton box width and height.
enum int pinsBaseW = 19; // Pins triangle base size.
enum int nMaxBalls = 55; // Number of balls.
static assert(boxW >= 2 && boxH >= 2);
static assert((boxW - 4) >= (pinsBaseW * 2 - 1))... |
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... | #Delphi | Delphi | -module(gapful).
-export([first_digit/1, last_digit/1, bookend_number/1, is_gapful/1]).
first_digit(N) ->
list_to_integer(string:slice(integer_to_list(N),0,1)).
last_digit(N) -> N rem 10.
bookend_number(N) -> 10 * first_digit(N) + last_digit(N).
is_gapful(N) -> (N >= 100) and (0 == N rem bookend_number(N)). |
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
| #F.23 | F# |
// Gaussian Elimination. Nigel Galloway: February 2nd., 2019
let gelim augM=
let f=List.length augM
let fG n (g:bigint list) t=n|>List.map(fun n->List.map2(fun n g->g-n)(List.map(fun n->n*g.[t])n)(List.map(fun g->g*n.[t])g))
let rec fN i (g::e as l)=
match i with i when i=f->l|>List.mapi(fun n (g:bigint lis... |
http://rosettacode.org/wiki/Generate_random_chess_position | Generate random chess position | Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any p... | #Yabasic | Yabasic | dim grid(8, 8)
sub placeKings()
local r1, r2, c1, c2
do
r1 = int(ran(8))
c1 = int(ran(8))
r2 = int(ran(8))
c2 = int(ran(8))
if (r1 <> r2 and abs(r1 - r2) > 1 and abs(c1 - c2) > 1) then
grid(r1, c1) = asc("K")
grid(r2, c2) = asc("k")
... |
http://rosettacode.org/wiki/Generate_random_chess_position | Generate random chess position | Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any p... | #zkl | zkl | fcn pickFEN{
# First we chose how many pieces to place: 2 to 32
n := (0).random(2,33);
# Then we pick $n squares: first n of shuffle (0,1,2,3...63)
n = [0..63].walk().shuffle()[0,n];
# We try to find suitable king positions on non-adjacent squares.
# If we could not find any, we return recursivel... |
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.
| #jq | jq | # Create an m x n matrix,
# it being understood that:
# matrix(0; _; _) evaluates to []
def matrix(m; n; init):
if m == 0 then []
elif m == 1 then [[range(0;n) | init]]
elif m > 0 then
[range(0;n) | init] as $row
| [range(0;m) | $row ]
else error("matrix\(m);_;_) invalid")
end;
def mprint($dec):
... |
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 ... | #Groovy | Groovy | def log = ''
(1..40).each {Integer value -> log +=(value %3 == 0) ? (value %5 == 0)? 'FIZZBUZZ\n':(value %7 == 0)? 'FIZZBAXX\n':'FIZZ\n'
:(value %5 == 0) ? (value %7 == 0)? 'BUZBAXX\n':'BUZZ\n'
:(value %7 == 0) ?'BAXX\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... | #Wren | Wren | var hailstone = Fn.new { |n|
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
var h = [n]
while (n != 1) {
n = (n%2 == 0) ? (n/2).floor : 3*n + 1
h.add(n)
}
return h
}
var h = hailstone.call(27)
System.print("For the Hailstone sequence starting with n = 27:")
Syste... |
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... | #Common_Lisp | Common Lisp | (defvar *lower*
(loop with a = (char-code #\a)
for i below 26
collect (code-char (+ a i)))) |
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... | #Cowgol | Cowgol | include "cowgol.coh";
# Generate the alphabet and store it at the given location
# It is assumed that there is enough space (27 bytes)
sub alph(buf: [uint8]): (out: [uint8]) is
out := buf;
var letter: uint8 := 'a';
while letter <= 'z' loop
[buf] := letter;
letter := letter + 1;
buf... |
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
| #Odin | Odin | package main
import "core:fmt"
main :: proc() {
fmt.println("Hellope!");
} |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Z80_Assembly | Z80 Assembly | push ix
push iy
pop ix ;the value that was once in IY is now in IX
pop iy ;the value that was once in IX is now in IY |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #zkl | zkl | class C{var v; fcn init(n){v=n}}
var c1=C(1), c2=C(2);
println(c1.v," : ",c2.v);
fcn swap(ca,cb,name){
tmp:=ca.resove(name);
ca.setVar(name,cb.resolve(name)); cb.setVar(name,tmp)
}
swap(c1,c2,"v");
println(c1.v," : ",c2.v); |
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... | #jq | jq | # Compute self^m where m is a non-negative integer:
def pow(m): . as $in | reduce range(0;m) as $i (1; .*$in);
# state: [i, i^m]
def next_power(m): .[0] + 1 | [., pow(m) ]; |
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... | #Wortel | Wortel | @gcd a b |
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... | #Wren | Wren | var gcd = Fn.new { |x, y|
while (y != 0) {
var t = y
y = x % y
x = t
}
return x.abs
}
System.print("gcd(33, 77) = %(gcd.call(33, 77))")
System.print("gcd(49865, 69811) = %(gcd.call(49865, 69811))") |
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... | #Perl | Perl | sub rnd($) { int(rand(shift)) }
sub empties { grep !$_[0][$_], 0 .. 7 }
sub chess960 {
my @s = (undef) x 8;
@s[2*rnd(4), 1 + 2*rnd(4)] = qw/B B/;
for (qw/Q N N/) {
my @idx = empties \@s;
$s[$idx[rnd(@idx)]] = $_;
}
@s[empties \@s] = qw/R K R/;
@s
}
print "@{[chess960]}\n" for 0 .. 10; |
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... | #11l | 11l | V compose = (f, g) -> (x -> @f(@g(x)))
V sin_asin = compose(x -> sin(x), x -> asin(x))
print(sin_asin(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.
| #BaCon | BaCon | OPTION PARSE FALSE
PRAGMA INCLUDE <curl/curl.h>
PRAGMA LDFLAGS -lcurl
DECLARE easyhandle TYPE CURL*
OPEN "data.txt" FOR WRITING AS download
easyhandle = curl_easy_init()
curl_easy_setopt(easyhandle, CURLOPT_URL, "ftp://localhost/pub/data.txt")
curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, download)
curl_easy_... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' The position regarding prototypes is broadly similar to that of the C language in that functions,
' sub-routines or operators (unless they have already been fully defined) must be declared before they can be used.
' This is usually done near the top of a file or in a separate header file which i... |
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... | #Go | Go | func a() // function with no arguments
func b(x, y int) // function with two arguments
func c(...int) // varargs are called "variadic parameters" in Go. |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
# calculate some members of the fusc sequence #
# f0 = 0, f1 = 1, fn = f(n/2) if n even #
# = f(n-1)/2) + f((n+1)/2) if n odd #
# constructs an array of the first n elements of the fusc sequence #
PROC fusc sequence = ( INT n )[]INT:
... |
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... | #Lua | Lua | -- DATA:
local function node(name, weight, coverage, children)
return { name=name, weight=weight or 1.0, coverage=coverage or 0.0, sumofweights=0, delta=0, children=children }
end
local root =
node("cleaning", nil, nil, {
node("house1", 40, nil, {
node("bedrooms", nil, 0.25),
node("bathrooms", nil, nil, {... |
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... | #Common_Lisp | Common Lisp | (defun mapc-tree (fn tree)
"Apply FN to all elements in TREE."
(cond ((consp tree)
(mapc-tree fn (car tree))
(mapc-tree fn (cdr tree)))
(t (funcall fn tree))))
(defun count-source (source)
"Load and count all function-bound symbols in a SOURCE file."
(load source)
(with-open-file (... |
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... | #AutoHotkey | AutoHotkey | /*
Here is the upper incomplete Gamma function. Omitting or setting
the second parameter to 0 we get the (complete) Gamma function.
The code is based on: "Computation of Special Functions" Zhang and Jin,
John Wiley and Sons, 1996
*/
SetFormat FloatFast, 0.9e
Loop 10
MsgBox % GAMMA(A_Index/3) "`n" GAMMA(A_Index... |
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 ... | #Elm | Elm | import Html.App exposing (program)
import Time exposing (Time, every, millisecond)
import Color exposing (Color, black, red, blue, green)
import Collage exposing (collage)
import Collage exposing (collage,polygon, filled, move, Form, circle)
import Element exposing (toHtml)
import Html exposing (Attribute, Html, text, ... |
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... | #Erlang | Erlang | -module(gapful).
-export([first_digit/1, last_digit/1, bookend_number/1, is_gapful/1]).
first_digit(N) ->
list_to_integer(string:slice(integer_to_list(N),0,1)).
last_digit(N) -> N rem 10.
bookend_number(N) -> 10 * first_digit(N) + last_digit(N).
is_gapful(N) -> (N >= 100) and (0 == N rem bookend_number(N)). |
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
| #Fortran | Fortran |
program ge
real, allocatable :: a(:,:),b(:)
a = reshape( &
[1.0, 1.00, 1.00, 1.00, 1.00, 1.00, &
0.0, 0.63, 1.26, 1.88, 2.51, 3.14, &
0.0, 0.39, 1.58, 3.55, 6.32, 9.87, &
0.0, 0.25, 1.98, 6.70, 15.88,... |
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.
| #Julia | Julia | A = [1 2 3; 4 1 6; 7 8 9]
@show I / A
@show inv(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 ... | #Haskell | Haskell | fizz :: (Integral a, Show a) => a -> [(a, String)] -> String
fizz a xs
| null result = show a
| otherwise = result
where result = concatMap (fizz' a) xs
fizz' a (factor, str)
| a `mod` factor == 0 = str
| otherwise = ""
main = do
line <- getLine
le... |
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... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int Seq(1000); \more than enough for longest sequence
func Hailstone(N); \Return length of Hailstone sequence starting at N
int N; \ also fills Seq array with sequence
int I;
[I:= 0;
loop [Seq(I):= N; I:= I+1;
if N=1 then ret... |
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... | #D | D | import std.ascii: lowercase;
void main() {} |
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... | #dc | dc | 122 [ d 1 - d 97<L 256 * + ] d sL x P |
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
| #Oforth | Oforth | "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... | #Julia | Julia | drop(gen::Function, n::Integer) = (for _ in 1:n gen() end; gen)
take(gen::Function, n::Integer) = collect(gen() for _ in 1:n)
function pgen(n::Number)
x = 0
return () -> (x += 1) ^ n
end
function genfilter(g1::Function, g2::Function)
local r1
local r2 = g2()
return () -> begin
r1 = g1()
... |
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... | #x86_Assembly | x86 Assembly | .text
.global pgcd
pgcd:
push %ebp
mov %esp, %ebp
mov 8(%ebp), %eax
mov 12(%ebp), %ecx
push %edx
.loop:
cmp $0, %ecx
je .end
xor %edx, %edx
div %ecx
mov %ecx, %eax
mov %edx, %ecx
... |
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... | #XBasic | XBasic | ' Greatest common divisor
PROGRAM "gcddemo"
VERSION "0.001"
DECLARE FUNCTION Entry()
DECLARE FUNCTION GcdRecursive(u&, v&)
DECLARE FUNCTION GcdIterative(u&, v&)
DECLARE FUNCTION GcdBinary(u&, v&)
FUNCTION Entry()
m& = 49865
n& = 69811
PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdIterative(m&, n&); " (ite... |
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... | #Phix | Phix | with javascript_semantics
sequence solutions = {}
--integer d = new_dict()
for i=1 to factorial(8) do
sequence s = permute(i,"RNBQKBNR")
-- sequence s = permute(rand(factorial(8),"RNBQKBNR")
integer b1 = find('B',s),
b2 = find('B',s,b1+1)
if and_bits(b2-b1,1)=1 then
integer k = find('... |
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... | #ActionScript | ActionScript | function compose(f:Function, g:Function):Function {
return function(x:Object) {return f(g(x));};
}
function test() {
trace(compose(Math.atan, Math.tan)(0.5));
} |
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... | #Ada | Ada | generic
type Argument is private;
package Functions is
type Primitive_Operation is not null
access function (Value : Argument) return Argument;
type Func (<>) is private;
function "*" (Left : Func; Right : Argument) return Argument;
function "*" (Left : Func; Right : Primitive_Operation) retu... |
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.
| #Batch_File | Batch File | ::Playing with FTP
::Batch File Implementation
@echo off
set site="ftp.hq.nasa.gov"
set user="anonymous"
set pass="ftptest@example.com"
set dir="pub/issoutreach/Living in Space Stories (MP3 Files)"
set download="Gravity in the Brain.mp3"
(
echo.open %site%
echo.user %user% %pass%
echo.dir
echo.!echo.
echo.!e... |
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 | C |
#include <ftplib.h>
int main(void)
{
netbuf *nbuf;
FtpInit();
FtpConnect("kernel.org", &nbuf);
FtpLogin("anonymous", "", nbuf);
FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);
FtpChdir("pub/linux/kernel", nbuf);
FtpDir((void*)0, ".", nbuf);
FtpGet("ftp.README", "README", FTPLIB_... |
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... | #Haskell | Haskell |
add :: Int -> Int -> Int
add x y = x+y
|
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... | #J | J | NB. j assumes an unknown name f is a verb of infinite rank
NB. f has infinite ranks
f b. 0
_ _ _
NB. The verb g makes a table.
g=: f/~
NB. * has rank 0
f=: *
NB. indeed, make a multiplication table
f/~ i.5
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
NB. g was defi... |
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 ... | #11l | 11l | F multiply(a, b)
R a * b |
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... | #BBC_BASIC | BBC BASIC | REM >frrepcal
:
DIM gregorian$(11)
DIM gregorian%(11)
DIM republican$(11)
DIM sansculottides$(5)
gregorian$() = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
gregorian%() = 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
REM 7-bit ASCII encoding,... |
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... | #AppleScript | AppleScript | on fusc(n)
if (n < 2) then
return n
else if (n mod 2 is 0) then
return fusc(n div 2)
else
return fusc((n - 1) div 2) + fusc((n + 1) div 2)
end if
end fusc
set sequence to {}
set longestSoFar to 0
repeat with i from 0 to 60
set fuscNumber to fusc(i)
set end of sequence t... |
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... | #Nim | Nim | import strformat, strutils
type
FCNode = ref object
name: string
weight: int
coverage: float
children: seq[FCNode]
parent: FCNode
func newFCNode(name: string; weight: int; coverage: float): FCNode =
FCNode(name: name, weight: weight, coverage: coverage)
# Forward reference.
func updateCo... |
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... | #Perl | Perl | use strict;
use warnings;
sub walktree {
my @parts;
while( $_[0] =~ /(?<head> (\s*) \N+\n ) # split off one level as 'head' (or terminal 'leaf')
(?<body> (?:\2 \s\N+\n)*)/gx ) { # next sub-level is 'body' (defined by extra depth of indentation)
my($head, $body) = ($+... |
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... | #Erlang | Erlang |
-module( function_frequency ).
-export( [erlang_source/1, task/0] ).
erlang_source( File ) ->
{ok, IO} = file:open( File, [read] ),
Forms = parse_all( IO, io:parse_erl_form(IO, ''), [] ),
Functions = lists:flatten( [erl_syntax_lib:fold(fun accumulate_functions/2, [], X) || X <- Forms] ),
dict:to_l... |
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... | #AWK | AWK |
# syntax: GAWK -f GAMMA_FUNCTION.AWK
BEGIN {
e = (1+1/100000)^100000
pi = atan2(0,-1)
leng = split("0.99999999999980993,676.5203681218851,-1259.1392167224028,771.32342877765313,-176.61502916214059,12.507343278686905,-0.13857109526572012,9.9843695780195716e-6,1.5056327351493116e-7",p,",")
print("X S... |
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 ... | #Factor | Factor | USING: accessors arrays calendar colors combinators
combinators.short-circuit fonts fry generalizations kernel
literals locals math math.ranges math.vectors namespaces opengl
random sequences timers ui ui.commands ui.gadgets
ui.gadgets.worlds ui.gestures ui.pens.solid ui.render ui.text ;
IN: rosetta-code.galton-box-ani... |
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... | #Factor | Factor | USING: formatting kernel lists lists.lazy math math.functions
math.text.utils sequences ;
: gapful? ( n -- ? )
dup 1 digit-groups [ first ] [ last 10 * + ] bi divisor? ;
30 100 15 1,000,000 10 1,000,000,000 [
2dup lfrom [ gapful? ] lfilter ltake list>array
"%d gapful numbers starting at %d:\n%[%d, %]\n\... |
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... | #Forth | Forth | variable cnt
: Int>Str s>d <# #s #> ;
: firstDigit C@ [char] 0 - ;
: lastDigit + 1- c@ [char] 0 - ;
: cnt++ cnt dup @ 1+ dup rot ! ;
: GapfulNumber? dup dup Int>Str
2dup drop firstDigit 10 *
... |
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
| #FreeBASIC | FreeBASIC |
Sub GaussJordan(matrix() As Double,rhs() As Double,ans() As Double)
Dim As Long n=Ubound(matrix,1)
Redim ans(0):Redim ans(1 To n)
Dim As Double b(1 To n,1 To n),r(1 To n)
For c As Long=1 To n 'take copies
r(c)=rhs(c)
For d As Long=1 To n
b(c,d)=matrix(c,d)
Next d
... |
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.
| #Kotlin | Kotlin | // version 1.2.21
typealias Matrix = Array<DoubleArray>
fun Matrix.inverse(): Matrix {
val len = this.size
require(this.all { it.size == len }) { "Not a square matrix" }
val aug = Array(len) { DoubleArray(2 * len) }
for (i in 0 until len) {
for (j in 0 until len) aug[i][j] = this[i][j]
... |
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 ... | #J | J | genfb=:1 :0
:
b=. * x|/1+i.y
>,&":&.>/(m#inv"_1~-.b),(*/b)#&.>1+i.y
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.