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/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... | #Logo | Logo | to bookend_number :n
output sum product 10 first :n last :n
end
to gapful? :n
output and greaterequal? :n 100 equal? 0 modulo :n bookend_number :n
end
to gapfuls_in_range :start :size
localmake "gapfuls []
do.while [
if (gapful? :start) [
make "gapfuls (lput :start gapfuls)
]
make "start s... |
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... | #LOLCODE | LOLCODE | HAI 1.2
HOW IZ I FurstDigit YR Numbr
I HAS A Digit
IM IN YR LOOP NERFIN YR Dummy WILE DIFFRINT Numbr AN 0
Digit R MOD OF Numbr AN 10
Numbr R QUOSHUNT OF Numbr AN 10
IM OUTTA YR LOOP
FOUND YR Digit
IF U SAY SO
HOW IZ I LastDigit YR Numbr
FOUND YR MOD OF Numbr AN 10
IF U SAY SO
HOW IZ I Bookend YR... |
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
| #Lambdatalk | Lambdatalk |
{require lib_matrix}
{M.solve
{M.new [[1.00,0.00,0.00,0.00,0.00,0.00],
[1.00,0.63,0.39,0.25,0.16,0.10],
[1.00,1.26,1.58,1.98,2.49,3.13],
[1.00,1.88,3.55,6.70,12.62,23.80],
[1.00,2.51,6.32,15.88,39.90,100.28],
[1.00,3.14,9.87,31.01,97.41,306.02]]}
[-0.01,0.61,0.91,0.... |
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.
| #Rust | Rust |
fn main() {
let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0],
vec![4.0, 1.0, 6.0],
vec![7.0, 8.0, 9.0]
];
let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0],
vec![-1.0, 2.0, -1.... |
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.
| #Sidef | Sidef | func gauss_jordan_invert (M) {
var I = M.len.of {|i|
M.len.of {|j|
i == j ? 1 : 0
}
}
var A = gather {
^M -> each {|i| take(M[i] + I[i]) }
}
rref(A).map { .last(M.len) }
}
var A = [
[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1... |
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 ... | #PHP | PHP | <?php
$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
for ($i = 1 ; $i <= $max ; $i++) {
$matched = false;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
}
echo ($matched ? '' : $i), PHP_EOL;
... |
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... | #Haskell | Haskell | lower = ['a' .. 'z']
main = print lower |
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... | #Huginn | Huginn | import Algorithms as algo;
import Text as text;
main() {
print(
"{}\n".format(
text.character_class( text.CHARACTER_CLASS.LOWER_CASE_LETTER )
)
);
print(
"{}\n".format(
algo.materialize(
algo.map(
algo.range( integer( 'a' ), integer( 'z' ) + 1 ),
character
... |
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
| #PDP-1_Assembly | PDP-1 Assembly |
hello
/ above: title line - was punched in human readable letters on paper tape
/ below: location specifier - told assembler what address to assemble to
100/
lup, lac i ptr / load ac from address stored in pointer
cli / clear io register
lu2, rcl 6s / rotate combined ac + io reg 6 bits to the left
/ left... |
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... | #PicoLisp | PicoLisp | (de powers (M)
(co (intern (pack 'powers M))
(for (I 0 (inc 'I))
(yield (** I M)) ) ) )
(de filtered (N M)
(co 'filtered
(let (V (powers N) F (powers M))
(loop
(if (> V F)
(setq F (powers M))
(and (> F V) (yield V))
(setq V ... |
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... | #XPL0 | XPL0 | char Col;
func ColNum(Start, Piece); \Return column number of Piece
int Start, Piece, I;
[for I:= Start to 7 do
if Col(I) = Piece then return I;
return -1;
];
proc Shuffle; \Randomly rearrange pieces in columns
int I, J, T;
[for I:= 8-1 downto 1 do
[J:= Ran(I); \range [0..I-1] (Sattol... |
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... | #zkl | zkl | const pieces="KQRrBbNN";
starts:=pieces:Utils.Helpers.permuteW(_).filter(fcn(p){
I:=p.index;
I("B") % 2 != I("b") % 2 and // Bishop constraint.
// King constraint.
((I("r") < I("K") and I("K") < I("R")) or
(I("R") < I("K") and I("K") < I("r")))
}).pump(List,"concat","toUpper"):Utils.Helpers.listUnique(_... |
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... | #Clojure | Clojure | (defn compose [f g]
(fn [x]
(f (g x))))
; Example
(def inc2 (compose inc inc))
(println (inc2 5)) ; prints 7 |
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... | #CoffeeScript | CoffeeScript |
compose = ( f, g ) -> ( x ) -> f g x
# Example
add2 = ( x ) -> x + 2
mul2 = ( x ) -> x * 2
mulFirst = compose add2, mul2
addFirst = compose mul2, add2
multiple = compose mul2, compose add2, mul2
console.log "add2 2 #=> #{ add2 2 }"
console.log "mul2 2 #=> #{ mul2 2 }"
console.log "mulFirst 2 #=> #{ mulFirst 2 }... |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #D | D | import std.stdio, std.math;
enum width = 1000, height = 1000; // Image dimension.
enum length = 400; // Trunk size.
enum scale = 6.0 / 10; // Branch scale relative to trunk.
void tree(in double x, in double y, in double length, in double angle) {
if (length < 1)
return;
imm... |
http://rosettacode.org/wiki/Fraction_reduction | Fraction reduction | There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simp... | #C.2B.2B | C++ | #include <array>
#include <iomanip>
#include <iostream>
#include <vector>
int indexOf(const std::vector<int> &haystack, int needle) {
auto it = haystack.cbegin();
auto end = haystack.cend();
int idx = 0;
for (; it != end; it = std::next(it)) {
if (*it == needle) {
return idx;
... |
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
... | #Bracmat | Bracmat | (fractran=
np n fs A Z fi P p N L M
. !arg:(?N,?n,?fs) {Number of iterations, start n, fractions}
& :?P:?L {Initialise accumulators.}
& whl
' ( -1+!N:>0:?N {Stop when counted down to zero.}
& !n !L:?L {Prepend all numbers... |
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.
| #Wren | Wren | /* ftp.wren */
var FTPLIB_CONNMODE = 1
var FTPLIB_PASSIVE = 1
var FTPLIB_ASCII = 65 // 'A'
foreign class Ftp {
foreign static init()
construct connect(host) {}
foreign login(user, pass)
foreign options(opt, val)
foreign chdir(path)
foreign dir(outputFile, path)
foreign ge... |
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.
| #zkl | zkl | zkl: var cURL=Import("zklCurl")
zkl: var d=cURL().get("ftp.hq.nasa.gov/pub/issoutreach/Living in Space Stories (MP3 Files)/")
L(Data(2,567),1630,23) // downloaded listing, 1630 bytes of header, 23 bytes of trailer
zkl: d[0][1630,-23].text
-rw-rw-r-- 1 109 space-station 2327118 May 9 2005 09sept_spacepropulsio... |
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 ... | #ALGOL_68 | ALGOL 68 | PROC multiply = ( LONG REAL a, b ) LONG REAL:
(
a * b
) |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} e... |
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... | #F.23 | F# |
open System
let gamma z =
let lanczosCoefficients = [76.18009172947146;-86.50532032941677;24.01409824083091;-1.231739572450155;0.1208650973866179e-2;-0.5395239384953e-5]
let rec sumCoefficients acc i coefficients =
match coefficients with
| [] -> acc
| h::t -> sumCoefficients (a... |
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 ... | #Phix | Phix | without js -- clear_screen(), text_color(), position(), sleep(), get_key()...
constant balls = 80
clear_screen()
sequence screen = repeat(repeat(' ',23),12)
& repeat(join(repeat(':',12)),12)
& {repeat('.',23)},
Pxy = repeat({12,1},balls)
for peg=1 to 10 do
screen[peg+2][13-p... |
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... | #Lua | Lua | function generateGaps(start, count)
local counter = 0
local i = start
print(string.format("First %d Gapful numbers >= %d :", count, start))
while counter < count do
local str = tostring(i)
local denom = 10 * tonumber(str:sub(1, 1)) + (i % 10)
if i % denom == 0 then
... |
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
| #Lobster | Lobster | import std
// test case from Go version at http://rosettacode.org/wiki/Gaussian_elimination
//
let ta = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00],
[1.00, 0.63, 0.39, 0.25, 0.16, 0.10],
[1.00, 1.26, 1.58, 1.98, 2.49, 3.13],
[1.00, 1.88, 3.55, 6.70, 12.62, 23.80],
[1.00, 2.51, 6.32, ... |
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.
| #VBA | VBA | Private Function inverse(mat As Variant) As Variant
Dim len_ As Integer: len_ = UBound(mat)
Dim tmp() As Variant
ReDim tmp(2 * len_ + 1)
Dim aug As Variant
ReDim aug(len_)
For i = 0 To len_
If UBound(mat(i)) <> len_ Then Debug.Print 9 / 0 '-- "Not a square matrix"
aug(i) = tmp
... |
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 ... | #Picat | Picat | interactive =>
print("> "),
MaxNum = read_int(),
Map = new_map(),
print("> "),
while (Line = read_line(), Line != "")
[N,V] = split(Line),
Map.put(N.to_int,V),
print("> ")
end,
general_fizzbuzz(MaxNum,Map.to_list.sort),
nl.
general_fizzbuzz(N,L) =>
FB = [I.to_string : I in 1..... |
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 ... | #PicoLisp | PicoLisp | (de general (N Lst)
(for A N
(prinl
(or
(extract
'((L)
(and (=0 (% A (car L))) (cdr L)) )
Lst )
A ) ) ) )
(general 20 '((3 . Fizz) (5 . Buzz) (7 . Baxx))) |
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... | #Icon_and_Unicon | Icon and Unicon | &lcase |
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... | #J | J | thru=: <. + i.@(+*)@-~
thru&.(a.&i.)/'az'
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
| #PDP-11_Assembly | PDP-11 Assembly | .globl start
.text
start:
mov $1,r0 / r0=stream, STDOUT=$1
sys 4; outtext; outlen / sys 4 is write
sys 1 / sys 1 is exit
rts pc / in case exit returns
.data
outtext: <Hello world!\n>
outlen = . - outtext |
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... | #PL.2FI | PL/I |
Generate: procedure options (main); /* 27 October 2013 */
declare j fixed binary;
declare r fixed binary;
/* Ignore the first 20 values */
do j = 1 to 20;
/* put edit (filter() ) (f(6)); */
r = filter ();
end;
put skip;
do j = 1 to 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... | #Common_Lisp | Common Lisp | (defun compose (f g) (lambda (x) (funcall f (funcall 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... | #Crystal | Crystal | require "math"
def compose(f : Proc(T, _), g : Proc(_, _)) forall T
return ->(x : T) { f.call(g.call(x)) }
end
compose(->Math.sin(Float64), ->Math.asin(Float64)).call(0.5) #=> 0.5 |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #EasyLang | EasyLang | func tree x y deg n . .
if n > 0
linewidth n * 0.4
move x y
x += cos deg * n * 1.3 * (randomf + 0.5)
y += sin deg * n * 1.3 * (randomf + 0.5)
line x y
call tree x y deg - 20 n - 1
call tree x y deg + 20 n - 1
.
.
timer 0
on timer
clear
call tree 50 90 -90 10
timer 1
. |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #F.23 | F# | let (cos, sin, pi) = System.Math.Cos, System.Math.Sin, System.Math.PI
let (width, height) = 1000., 1000. // image dimension
let scale = 6./10. // branch scale relative to trunk
let length = 400. // trunk size
let rec tree x y length angle =
if length >= 1. then
let (x2, ... |
http://rosettacode.org/wiki/Fraction_reduction | Fraction reduction | There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simp... | #D | D | import std.range;
import std.stdio;
int indexOf(Range, Element)(Range haystack, scope Element needle)
if (isInputRange!Range) {
int idx;
foreach (straw; haystack) {
if (straw == needle) {
return idx;
}
idx++;
}
return -1;
}
bool getDigits(int n, int le, int[] digi... |
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
... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
typedef struct frac_s *frac;
struct frac_s {
int n, d;
frac next;
};
frac parse(char *s)
{
int offset = 0;
struct frac_s h = {0}, *p = &h;
while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) {
s += offset;
p = p->next = malloc(sizeof *p);
*p = ... |
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 ... | #ALGOL_W | ALGOL W | long real procedure multiply( long real value a, b );
begin
a * b
end |
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... | #Go | Go | package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} e... |
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... | #Factor | Factor | ! built in
USING: picomath prettyprint ;
0.1 gamma . ! 9.513507698668723
2.0 gamma . ! 1.0
10. gamma . ! 362880.0 |
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 ... | #PicoLisp | PicoLisp | (de galtonBox (Pins Height)
(let (Bins (need (inc (* 2 Pins)) 0) X 0 Y 0)
(until (= Height (apply max Bins))
(call 'clear)
(cond
((=0 Y) (setq X (inc Pins) Y 1))
((> (inc 'Y) Pins)
(inc (nth Bins X))
(zero Y) ) )
((if (rand T) ... |
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 ... | #Prolog | Prolog | :- dynamic tubes/1.
:- dynamic balls/2.
:- dynamic stop/1.
% number of rows of pins (0 -> 9)
row(9).
galton_box :-
retractall(tubes(_)),
retractall(balls(_,_)),
retractall(stop(_)),
assert(stop(@off)),
new(D, window('Galton Box')),
send(D, size, size(520,700)),
display_pins(D),
new(ChTubes, chain),
assert(... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[GapFulQ]
GapFulQ[n_Integer] := Divisible[n, FromDigits[IntegerDigits[n][[{1, -1}]]]]
i = 100;
res = {};
While[Length[res] < 30,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res
i = 10^6;
res = {};
While[Length[res] < 15,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res
i = 10^9;
res = {};
While[Length[res] < 10,
... |
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... | #min | min | (() 0 shorten) :new
(((10 mod) (10 div)) cleave) :moddiv
((dup 0 ==) (pop new) 'moddiv 'cons linrec) :digits
(digits ((last 10 *) (first +)) cleave) :flnum
(mod 0 ==) :divisor?
(dup flnum divisor?) :gapful?
(
:target :n 0 :count
"$1 gapful numbers starting at $2:" (target n) => % puts!
(count target <) (
(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
| #M2000_Interpreter | M2000 Interpreter |
module checkit {
Dim Base 1, a(6, 6), b(6)
a(1,1)= 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02
\\ remove \\ to feed nex... |
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.
| #VBScript | VBScript | ' Gauss-Jordan matrix inversion - VBScript - 22/01/2021
Option Explicit
Function rref(m)
Dim r, c, i, n, div, wrk
n=UBound(m)
For r = 1 To n 'row
div = m(r,r)
If div <> 0 Then
For c = 1 To n*2 'col
m(r,c) = m(r,c) / div
Next 'c
Else
... |
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 ... | #PowerShell | PowerShell | $limit = 20
$data = @("3 Fizz","5 Buzz","7 Baxx")
#An array with whitespace as the delimiter
#Between the factor and the word
for ($i = 1;$i -le $limit;$i++){
$outP = ""
foreach ($x in $data){
$data_split = $x -split " " #Split the "<factor> <word>"
if (($i % $data_split[0]) -eq 0){
$outP += $data_split[1... |
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... | #Java | Java | public class LowerAscii {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(26);
for (char ch = 'a'; ch <= 'z'; ch++)
sb.append(ch);
System.out.printf("lower ascii: %s, length: %s", sb, sb.length());
}
} |
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... | #JavaScript | JavaScript | (function (cFrom, cTo) {
function cRange(cFrom, cTo) {
var iStart = cFrom.charCodeAt(0);
return Array.apply(
null, Array(cTo.charCodeAt(0) - iStart + 1)
).map(function (_, i) {
return String.fromCharCode(iStart + i);
});
}
return cRange(cFrom, cTo);
})('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
| #PepsiScript | PepsiScript | #include default-libraries
#author Childishbeat
class Hello world/Text:
function Hello world/Text:
print "Hello world!"
end |
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... | #Python | Python | from itertools import islice, count
def powers(m):
for n in count():
yield n ** m
def filtered(s1, s2):
v, f = next(s1), next(s2)
while True:
if v > f:
f = next(s2)
continue
elif v < f:
yield v
v = next(s1)
squares, cubes = powers(2),... |
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... | #D | D | import std.stdio;
T delegate(S) compose(T, U, S)(in T delegate(U) f,
in U delegate(S) g) {
return s => f(g(s));
}
void main() {
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10));
writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(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... | #Delphi | Delphi | program AnonCompose;
{$APPTYPE CONSOLE}
type
TFunc = reference to function(Value: Integer): Integer;
// Alternative: TFunc = TFunc<Integer,Integer>;
function Compose(F, G: TFunc): TFunc;
begin
Result:= function(Value: Integer): Integer
begin
Result:= F(G(Value));
end
end;
var
Func1, Func2, Func3... |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #Fantom | Fantom |
using fwt
using gfx
class FractalCanvas : Canvas
{
new make () : super() {}
Void drawTree (Graphics g, Int x1, Int y1, Int angle, Int depth)
{
if (depth == 0) return
Int x2 := x1 + (angle.toFloat.toRadians.cos * depth * 10.0).toInt;
Int y2 := y1 + (angle.toFloat.toRadians.sin * depth * 10.0).to... |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #FreeBASIC | FreeBASIC | ' version 17-03-2017
' compile with: fbc -s gui
Const As Double deg2rad = Atn(1) / 45
Dim Shared As Double scale = 0.76
Dim Shared As Double spread = 25 * deg2rad ' convert degree's to rad's
Sub branch(x1 As ULong, y1 As ULong, size As ULong, angle As Double, depth As ULong)
Dim As ULong x2, y2
x2 = x1 ... |
http://rosettacode.org/wiki/Fraction_reduction | Fraction reduction | There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simp... | #Delphi | Delphi | package main
import (
"fmt"
"time"
)
func indexOf(n int, s []int) int {
for i, j := range s {
if n == j {
return i
}
}
return -1
}
func getDigits(n, le int, digits []int) bool {
for n > 0 {
r := n % 10
if r == 0 || indexOf(r, digits) >= 0 {
... |
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
... | #C.2B.2B | C++ |
#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <cmath>
using namespace std;
class fractran
{
public:
void run( std::string p, int s, int l )
{
start = s; limit = l;
istringstream iss( p ); vector<string> tmp;
copy( istream_iterator<string>( i... |
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 ... | #ALGOL-M | ALGOL-M | INTEGER FUNCTION MULTIPLY( A, B );
INTEGER A, B;
BEGIN
MULTIPLY := A * B;
END; |
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... | #Groovy | Groovy | class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its... |
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... | #Forth | Forth | 8 constant (gamma-shift)
: (mortici) ( f1 -- f2)
-1 s>f f+ 1 s>f
fover 271828183e-8 f* 12 s>f f* f/
fover 271828183e-8 f/ f+
fover f** fswap
628318530e-8 f* fsqrt f* \ 2*pi
;
: gamma ( f1 -- f2)
fdup f0< >r fdup f0= r> or abort" Gamma... |
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 ... | #PureBasic | PureBasic | Global pegRadius, pegSize, pegSize2, height, width, delay, histogramSize, ball
Procedure eventLoop()
Protected event
Repeat
event = WindowEvent()
If event = #PB_Event_CloseWindow
End
EndIf
Until event = 0
EndProcedure
Procedure animate_actual(x1, y1, x2, y2, steps)
Protected x.f, y.f, xst... |
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... | #newLISP | newLISP | ; Part 1: Useful functions
;; Create an integer out of the first and last digits of a given integer
(define (first-and-last-digits number)
(local (digits first-digit last-digit)
(set 'digits (format "%d" number))
(set 'first-digit (first digits))
(set 'last-digit (last digits))
(int (append first-digit last-... |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | GaussianElimination[A_?MatrixQ, b_?VectorQ] := Last /@ RowReduce[Flatten /@ Transpose[{A, b}]] |
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.
| #Wren | Wren | import "/matrix" for Matrix
import "/fmt" for Fmt
var arrays = [
[ [ 1, 2, 3],
[ 4, 1, 6],
[ 7, 8, 9] ],
[ [ 2, -1, 0 ],
[-1, 2, -1 ],
[ 0, -1, 2 ] ],
[ [ -1, -2, 3, 2 ],
[ -4, -1, 6, 2 ],
[ 7, -8, 9, 1 ],
[ 1, -2, 1, 3 ] ]
]
for (array in arrays)... |
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 ... | #Prolog | Prolog | maxNumber(105).
factors([(3, "Fizz"), (5, "Buzz"), (7, "Baxx")]). |
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 ... | #Python | Python | def genfizzbuzz(factorwords, numbers):
# sort entries by factor
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
retu... |
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... | #jq | jq | "az" | explode | [range( .[0]; 1+.[1] )] | implode' |
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... | #Jsish | Jsish | /* Generate the lower case alphabet with Jsish, assume ASCII */
var letterA = "a".charCodeAt(0);
var lowers = Array(26);
for (var i = letterA; i < letterA + 26; i++) {
lowers[i - letterA] = Util.fromCharCode(i);
}
puts(lowers);
puts(lowers.join(''));
puts(lowers.length);
/*
=!EXPECTSTART!=
[ "a", "b", "c", "d", "... |
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
| #Perl | Perl | print "Hello world!\n"; |
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... | #Quackery | Quackery | [ ' [ this -1 peek
this -2 peek **
1 this tally
done ]
swap join
0 join ] is expogen ( n --> [ )
[ ' [ this temp put
temp share -3 peek do
dup temp share share = iff
[ drop
temp share -2 peek do
temp take... |
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... | #Diego | Diego | set_namespace(rosettacode);
begin_funct(compose)_arg(f, g);
[]_ret(x)_calc([f]([g]([x])));
end_funct[];
me_msg()_funct(compose)_arg(f)_sin()_arg(g)_asin()_var(x)_value(0.5); // result: 0.5
reset_namespace[]; |
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... | #Dylan | Dylan |
define method compose(f,g)
method(x) f(g(x)) end
end;
|
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #Frege | Frege | module FractalTree where
import Java.IO
import Prelude.Math
data AffineTransform = native java.awt.geom.AffineTransform where
native new :: () -> STMutable s AffineTransform
native clone :: Mutable s AffineTransform -> STMutable s AffineTransform
native rotate :: Mutable s AffineTransform -> Double -> ST s ()... |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #Frink | Frink |
// Draw Fractal Tree in Frink
// Define the tree function
FractalTree[x1, y1, angleval, lengthval, graphicsobject] :=
{
if lengthval > 1
{
// Define current line end points (x2 and y2)
x2 = x1 + ((cos[angleval degrees]) * lengthval)
y2 = y1 + ((sin[angleval degrees]) * lengthval)
// Dr... |
http://rosettacode.org/wiki/Fraction_reduction | Fraction reduction | There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simp... | #Go | Go | package main
import (
"fmt"
"time"
)
func indexOf(n int, s []int) int {
for i, j := range s {
if n == j {
return i
}
}
return -1
}
func getDigits(n, le int, digits []int) bool {
for n > 0 {
r := n % 10
if r == 0 || indexOf(r, digits) >= 0 {
... |
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
... | #Common_Lisp | Common Lisp | (defun fractran (n frac-list)
(lambda ()
(prog1
n
(when n
(let ((f (find-if (lambda (frac)
(integerp (* n frac)))
frac-list)))
(when f (setf n (* f n))))))))
;; test
(defvar *primes-ft* '(17/91 78/85 19/51 23/38 29/33 77/29 ... |
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 ... | #AmigaE | AmigaE | PROC my_molt(a,b)
-> other statements if needed... here they are not
ENDPROC a*b -> return value
-> or simplier
PROC molt(a,b) IS a*b
PROC main()
WriteF('\d\n', my_molt(10,20))
ENDPROC |
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... | #Haskell | Haskell | ---------------------- FUSC SEQUENCE ---------------------
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
--------------------------- TEST --------... |
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... | #Fortran | Fortran | program ComputeGammaInt
implicit none
integer :: i
write(*, "(3A15)") "Simpson", "Lanczos", "Builtin"
do i=1, 10
write(*, "(3F15.8)") my_gamma(i/3.0), lacz_gamma(i/3.0), gamma(i/3.0)
end do
contains
pure function intfuncgamma(x, y) result(z)
real :: z
real, intent(in) :: x, y
z ... |
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 ... | #Python | Python | #!/usr/bin/python
import sys, os
import random
import time
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
class Ball():
def __init__(self):
self.x = 0
self.y = 0
def update(self):
self.x += random.randint(0,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... | #Nim | Nim | import strutils
func gapfulDivisor(n: Positive): Positive =
## Return the gapful divisor of "n".
let last = n mod 10
var first = n div 10
while first > 9:
first = first div 10
result = 10 * first + last
iterator gapful(start: Positive): Positive =
## Yield the gapful numbers starting from "sta... |
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... | #Pascal | Pascal | program gapful;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils // IntToStr
{$IFDEF FPC}
,strUtils // Numb2USA aka commatize
{$ENDIF};
const
cIdx = 5;
starts: array[0..cIdx - 1] of Uint64 = (100, 1000 * 1000, 10 * 1000 * 1000,
1000 * 1000 * 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
| #MATLAB | MATLAB |
function [ x ] = GaussElim( A, b)
% Ensures A is n by n
sz = size(A);
if sz(1)~=sz(2)
fprintf('A is not n by n\n');
clear x;
return;
end
n = sz(1);
% Ensures b is n x 1.
if n~=sz(1)
fprintf('b is not 1 by n.\n');
return
end
x = zeros(n,1);
aug = [A b];
tempmatrix = aug;
for i=2:sz(1)
... |
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.
| #zkl | zkl | var [const] GSL=Import.lib("zklGSL"); // libGSL (GNU Scientific Library)
m:=GSL.Matrix(3,3).set(1,2,3, 4,1,6, 7,8,9);
i:=m.invert();
i.format(10,4).println("\n");
(m*i).format(10,4).println(); |
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 ... | #R | R | genFizzBuzz <- function(n, ...)
{
args <- list(...)
#R doesn't like vectors of mixed types, so c(3, "Fizz") is coerced to c("3", "Fizz"). We must undo this.
#Treating "[[" as if it is a function is a bit of R's magic. You can treat it like a function because it actually is one.
factors <- as.integer(sapply(args... |
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... | #Julia | Julia | @show collect('a':'z')
@show join('a':'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... | #K | K | `c$97+!26 |
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
| #Peylang | Peylang | chaap '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... | #R | R | powers = function(m)
{n = -1
function()
{n <<- n + 1
n^m}}
noncubic.squares = local(
{squares = powers(2)
cubes = powers(3)
cube = cubes()
function()
{square = squares()
while (1)
{if (square > cube)
{cube <<- cubes()
next}
... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | compose f g:
labda:
f g |
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... | #E | E | def compose(f, g) {
return fn x { return f(g(x)) }
} |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #Go | Go | package main
// Files required to build supporting package raster are found in:
// * Bitmap
// * Grayscale image
// * Xiaolin Wu's line algorithm
// * Write a PPM file
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
fu... |
http://rosettacode.org/wiki/Fraction_reduction | Fraction reduction | There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simp... | #Groovy | Groovy | class FractionReduction {
static void main(String[] args) {
for (int size = 2; size <= 5; size++) {
reduce(size)
}
}
private static void reduce(int numDigits) {
System.out.printf("Fractions with digits of length %d where cancellation is valid. Examples:%n", numDigits)
... |
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
... | #D | D | import std.stdio, std.algorithm, std.conv, std.array;
void fractran(in string prog, int val, in uint limit) {
const fracts = prog.split.map!(p => p.split("/").to!(int[])).array;
foreach (immutable n; 0 .. limit) {
writeln(n, ": ", val);
const found = fracts.find!(p => val % p[1] == 0);
... |
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 ... | #AntLang | AntLang | multiply: * /`*' is a normal function
multiply: {x * y} |
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... | #J | J |
fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
NB. show the first 61 fusc numbers (starting at zero) in a horizontal format.
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 ... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Const pi = 3.1415926535897932
Const e = 2.7182818284590452
Function gammaStirling (x As Double) As Double
Return Sqr(2.0 * pi / x) * ((x / e) ^ x)
End Function
Function gammaLanczos (x As Double) As Double
Dim p(0 To 8) As Double = _
{ _
0.99999999999980993, _
676.5203681218... |
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 ... | #Racket | Racket |
;a ball's position...row is a natural number and col is an integer where 0 is the center
(define-struct pos (row col))
;state of simulation...list of all positions and vector of balls (index = bin)
(define-struct st (poss bins))
;increment vector @i
(define (vector-inc! v i) (vector-set! v i (add1 (vector-ref v i))))... |
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 ... | #Raku | Raku | my $row-count = 6;
constant $peg = "*";
constant @coin-icons = "\c[UPPER HALF BLOCK]", "\c[LOWER HALF BLOCK]";
sub display-board(@positions, @stats is copy, $halfstep) {
my $coin = @coin-icons[$halfstep.Int];
state @board-tmpl = {
# precompute a board
my @tmpl;
sub out(*@stuff) {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.