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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub is_gapful { my $n = shift; 0 == $n % join('', (split //, $n)[0,-1]) }
use constant Inf => 1e10;
for ([1e2, 30], [1e6, 15], [1e9, 10], [7123, 25]) {
my($start, $count) = @$_;
printf "\nFir... |
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
| #Modula-3 | Modula-3 | GENERIC INTERFACE Matrix(RingElem);
(*
"RingElem" must export the following:
- a type T;
- procedures
+ "Nonzero(a: T): BOOLEAN", which indicates whether "a" is nonzero;
+ "Minus(a, b: T): T" and "Times(a, b: T): T",
which return the results you'd guess from the procedures' names; and
+ "Print(a: T)", which... |
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 ... | #Racket | Racket | #lang racket/base
(define (get-matches num factors/words)
(for*/list ([factor/word (in-list factors/words)]
[factor (in-value (car factor/word))]
[word (in-value (cadr factor/word))]
#:when (zero? (remainder num factor)))
word))
(define (gen-fizzbuzz from to factors/... |
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 ... | #Raku | Raku | # General case implementation of a "FizzBuzz" class.
# Defaults to standard FizzBuzz unless a new schema is passed in.
class FizzBuzz {
has $.schema is rw = < 3 Fizz 5 Buzz >.hash;
method filter (Int $this) {
my $fb;
for $.schema.sort: { +.key } -> $p { $fb ~= $this %% +$p.key ?? $p.value !! ''}... |
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... | #Keg | Keg | a(55*|: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... | #Kotlin | Kotlin | // version 1.3.72
fun main() {
val alphabet = CharArray(26) { (it + 97).toChar() }.joinToString("")
println(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
| #Pharo | Pharo | "Comments are in double quotes"
"Sending message printString to 'Hello World' string"
'Hello World' printString |
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... | #Racket | Racket |
#lang racket
(require racket/generator)
;; this is a function that returns a powers generator, not a generator
(define (powers m)
(generator ()
(for ([n (in-naturals)]) (yield (expt n m)))))
(define squares (powers 2))
(define cubes (powers 3))
;; same here
(define (filtered g1 g2)
(generator ()
... |
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... | #EchoLisp | EchoLisp |
;; By decreasing order of performance
;; 1) user definition : lambda and closure
(define (ucompose f g ) (lambda (x) ( f ( g x))))
(ucompose sin cos)
→ (🔒 λ (_x) (f (g _x)))
;; 2) built-in compose : lambda
(compose sin cos)
→ (λ (_#:g1002) (#apply-compose (#list #cos #sin) _#:g1002))
;; 3) compiled com... |
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... | #Ela | Ela | let compose f g x = 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
| #Haskell | Haskell | import Graphics.Gloss
type Model = [Picture -> Picture]
fractal :: Int -> Model -> Picture -> Picture
fractal n model pict = pictures $ take n $ iterate (mconcat model) pict
tree1 _ = fractal 10 branches $ Line [(0,0),(0,100)]
where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate 30
... |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
WOpen("size=800,600", "bg=black", "fg=white") | stop("*** cannot open window")
drawtree(400,500,-90,9)
WDone()
end
link WOpen
procedure drawtree(x,y,angle,depth)
if depth > 0 then {
x2 := integer(x + cos(dtor(angle)) * depth * 10)
y2 := integer(y + sin(dtor(angle)) * depth * 10)
DrawLine(x... |
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... | #Haskell | Haskell | import Control.Monad (guard)
import Data.List (intersect, unfoldr, delete, nub, group, sort)
import Text.Printf (printf)
type Fraction = (Int, Int)
type Reduction = (Fraction, Fraction, Int)
validIntegers :: [Int] -> [Int]
validIntegers xs = [x | x <- xs, not $ hasZeros x, hasUni... |
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
... | #Delphi | Delphi |
program FractranTest;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.RegularExpressions;
type
TFractan = class
private
limit: Integer;
num, den: TArray<Integer>;
procedure compile(prog: string);
procedure exec(val: Integer);
function step(val: Integer): integer;
procedure dump()... |
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 ... | #APL | APL |
⍝⍝ APL2 'tradfn' (traditional function)
⍝⍝ This syntax works in all dialects including GNU APL and Dyalog.
∇ product ← a multiply b
product ← a × b
∇
⍝⍝ A 'dfn' or 'lambda' (anonymous function)
multiply ← {⍺×⍵}
|
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... | #Java | Java |
public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nSho... |
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... | #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(" x math.Gamma Lanczos7")
for _, x := range []float64{-.5, .1, .5, 1, 1.5, 2, 3, 10, 140, 170} {
fmt.Printf("%5.1f %24.16g %24.16g\n", x, math.Gamma(x), lanczos7(x))
}
}
func lanczos7(z floa... |
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 ... | #REXX | REXX | /*REXX pgm simulates Sir Francis Galton's box, aka: Galton Board, quincunx, bean machine*/
trace off /*suppress any messages for negative RC*/
if !all(arg()) then exit /*Any documentation was wanted? Done.*/
signal on halt ... |
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... | #Phix | Phix | constant starts = {1e2, 1e6, 1e7, 1e9, 7123},
counts = {30, 15, 15, 10, 25}
for i=1 to length(starts) do
integer count = counts[i],
j = starts[i],
pow = 100
while j>=pow*10 do pow *= 10 end while
printf(1,"First %d gapful numbers starting at %,d: ", {count, j})
while... |
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
| #Nim | Nim | const Eps = 1e-14 # Tolerance required.
type
Vector[N: static Positive] = array[N, float]
Matrix[M, N: static Positive] = array[M, Vector[N]]
SquareMatrix[N: static Positive] = Matrix[N, N]
func gaussPartialScaled(a: SquareMatrix; b: Vector): Vector =
doAssert a.N == b.N, "matrix and vector have incom... |
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 ... | #Red | Red | Red ["FizzBuzz"]
nmax: to-integer ask "Max number: "
while ["" <> trim rule: ask "New rule (empty to end): "][
append rules: [] load rule
]
repeat n nmax [
res: copy ""
foreach [x blah] rules [
if n % x = 0 [append res blah]
]
print either empty? res [n] [res]
]
halt |
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 ... | #REXX | REXX | /*REXX program shows a generalized FizzBuzz program: #1 name1 #2 name2 ··· */
parse arg h $ /*obtain optional arguments from the CL*/
if h='' | h="," then h= 20 /*Not specified? Then use the default.*/
if $='' | $="," then $= "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... | #Lambdatalk | Lambdatalk |
1) We define code2char & char2code as primitives:
{script
LAMBDATALK.DICT["char2code"] = function() {
var args = arguments[0].trim();
return args.charCodeAt(0);
};
LAMBDATALK.DICT["code2char"] = function() {
var args = arguments[0].trim();
return String.fromCharCode(args);
};
}
2) and we use them:
... |
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
| #Phix | Phix | puts(1,"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... | #Raku | Raku | sub powers($m) { $m XR** 0..* }
my @squares = powers(2);
my @cubes = powers(3);
sub infix:<with-out> (@orig,@veto) {
gather for @veto -> $veto {
take @orig.shift while @orig[0] before $veto;
@orig.shift if @orig[0] eqv $veto;
}
}
say (@squares with-out @cubes)[20 ..^ 20+10].join(', '); |
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... | #Elena | Elena | import extensions;
extension op : Func1
{
compose(Func1 f)
= (x => self(f(x)));
}
public program()
{
var fg := (x => x + 1).compose:(x => x * x);
console.printLine(fg(3))
} |
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... | #Elixir | Elixir | defmodule RC do
def compose(f, g), do: fn(x) -> f.(g.(x)) end
def multicompose(fs), do: List.foldl(fs, fn(x) -> x end, &compose/2)
end
sin_asin = RC.compose(&:math.sin/1, &:math.asin/1)
IO.puts sin_asin.(0.5)
IO.puts RC.multicompose([&:math.sin/1, &:math.asin/1, fn x->1/x end]).(0.5)
IO.puts RC.multicompose([... |
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
| #J | J | require'gl2'
coinsert'jgl2'
L0=: 50 NB. initial length
A0=: 1r8p1 NB. initial angle: pi divided by 8
dL=: 0.9 NB. shrink factor for length
dA=: 0.75 NB. shrink factor for angle
N=: 14 NB. number of branches
L=: L0*dL^1+i.N NB. lengths of line segments
NB. relative ang... |
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
| #Java | Java | import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class FractalTree extends JFrame {
public FractalTree() {
super("Fractal Tree");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private voi... |
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... | #J | J |
Filter=: (#~`)(`:6)
assert 'ac' -: 1 0 1"_ Filter 'abc'
intersect=:-.^:2
assert 'ab' -: 'abc'intersect'razb'
odometer=: (4$.$.)@:($&1)
Note 'odometer 2 3'
0 0
0 1
0 2
1 0
1 1
1 2
)
common=: 0 e. ~:
assert common 1 2 1
assert -. common 1 2 3
o=: '123456789' {~ [: -.@:common"1 Filter odometer@:(#&9) NB. o is y ... |
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
... | #Elixir | Elixir | defmodule Fractran do
use Bitwise
defp binary_to_ratio(b) do
[_, num, den] = Regex.run(~r/(\d+)\/(\d+)/, b)
{String.to_integer(num), String.to_integer(den)}
end
def load(program) do
String.split(program) |> Enum.map(&binary_to_ratio(&1))
end
defp step(_, []), do: :halt
defp step(n, [f|fs... |
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 ... | #AppleScript | AppleScript | to multiply(a as number, b as number)
return 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... | #JavaScript | JavaScript | (() => {
"use strict";
// ---------------------- FUSC -----------------------
// fusc :: Int -> Int
const fusc = i => {
const go = n =>
0 === n ? [
1, 0
] : (() => {
const [x, y] = go(Math.floor(n / 2));
return 0 === n... |
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... | #Groovy | Groovy | a = [ 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108,
-0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675,
-0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511,
-0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824,
... |
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 ... | #Ruby | Ruby | $rows_of_pins = 12
$width = $rows_of_pins * 10 + ($rows_of_pins+1)*14
Shoes.app(
:width => $width + 14,
:title => "Galton Box"
) do
@bins = Array.new($rows_of_pins+1, 0)
@x_coords = Array.new($rows_of_pins) {Array.new}
@y_coords = Array.new($rows_of_pins)
stack(:width => $width) do
stroke gray
... |
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... | #Plain_English | Plain English | To run:
Start up.
Show the gapful numbers at various spots.
Wait for the escape key.
Shut down.
A digit is a number.
To get a digit of a number (last):
Privatize the number.
Divide the number by 10 giving a quotient and a remainder.
Put the remainder into the digit.
To get a digit of a number (first):
Privatize t... |
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
| #OCaml | OCaml |
module Array = struct
include Array
(* Computes: f a.(0) + f a.(1) + ... where + is 'g'. *)
let foldmap g f a =
let n = Array.length a in
let rec aux acc i =
if i >= n then acc else aux (g acc (f a.(i))) (succ i)
in aux (f a.(0)) 1
(* like the stdlib fold_left, but also provides index to f... |
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 ... | #Ring | Ring |
limit = 20
for n = 1 to limit
if n % 3 = 0 see "" + n + " = " + "Fizz"+ nl
but n % 5 = 0 see "" + n + " = " + "Buzz" + nl
but n % 7 = 0 see "" + n + " = " + "Baxx" + nl
else see "" + n + " = " + n + nl ok
next
|
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 ... | #Ruby | Ruby | def general_fizzbuzz(text)
num, *nword = text.split
num = num.to_i
dict = nword.each_slice(2).map{|n,word| [n.to_i,word]}
(1..num).each do |i|
str = dict.map{|n,word| word if i%n==0}.join
puts str.empty? ? i : str
end
end
text = <<EOS
20
3 Fizz
5 Buzz
7 Baxx
EOS
general_fizzbuzz(text) |
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... | #LC3_Assembly | LC3 Assembly | .ORIG 0x3000
LD R0,ASCIIa
LD R1,ASCIIz
NOT R1,R1
LOOP OUT
ADD R0,R0,1
ADD R2,R0,R1
BRN LOOP
HALT
ASCIIa .FILL 0x61
ASCIIz .FILL 0x7A |
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... | #Lingo | Lingo | alphabet = []
repeat with i = 97 to 122
alphabet.add(numtochar(i))
end repeat
put alphabet
-- ["a", "b", "c", ... , "x", "y", "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
| #PHL | PHL | module helloworld;
extern printf;
@Integer main [
printf("Hello world!");
return 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... | #REXX | REXX | /*REXX program demonstrates how to use a generator (also known as an iterator). */
parse arg N .; if N=='' | N=="," then N=20 /*N not specified? Then use default.*/
@.= /* [↓] calculate squares,cubes,pureSq.*/
do i=1 for N; call Gsquare i
... |
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... | #Emacs_Lisp | Emacs Lisp | ;; lexical-binding: t
(defun compose (f g)
(lambda (x)
(funcall f (funcall g x))))
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 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... | #Erlang | Erlang | -module(fn).
-export([compose/2, multicompose/1]).
compose(F,G) -> fun(X) -> F(G(X)) end.
multicompose(Fs) ->
lists:foldl(fun compose/2, fun(X) -> X end, Fs). |
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
| #JavaScript | JavaScript | <html>
<body>
<canvas id="canvas" width="600" height="500"></canvas>
<script type="text/javascript">
var elem = document.getElementById('canvas');
var context = elem.getContext('2d');
context.fillStyle = '#C0C0C0';
context.lineWidth = 1;
var deg_to_rad = Math.PI / 180.0;
var depth = 9;
function drawLine(x1, y1,... |
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... | #Java | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FractionReduction {
public static void main(String[] args) {
for ( int size = 2 ; size <= 5 ; size++ ) {
reduce(size);
}
}
private... |
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
... | #Erlang | Erlang | #! /usr/bin/escript
-mode(native).
-import(lists, [map/2, reverse/1]).
binary_to_ratio(B) ->
{match, [_, Num, Den]} = re:run(B, "([0-9]+)/([0-9]+)"),
{binary_to_integer(binary:part(B, Num)),
binary_to_integer(binary:part(B, Den))}.
load(Program) ->
map(fun binary_to_ratio/1, re:split(Program, "[ ... |
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 ... | #Applesoft_BASIC | Applesoft BASIC | 10 DEF FN MULTIPLY(P) = P(P) * P(P+1)
20 P(1) = 611 : P(2) = 78 : PRINT FN MULTIPLY(1) |
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... | #jq | jq | # input should be a non-negative integer
def commatize:
# "," is 44
def digits: tostring | explode | reverse;
[foreach digits[] as $d (-1; .+1;
(select(. > 0 and . % 3 == 0)|44), $d)]
| reverse | implode ;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; |
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... | #Julia | Julia | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc ... |
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... | #Haskell | Haskell | cof :: [Double]
cof =
[ 76.18009172947146
, -86.50532032941677
, 24.01409824083091
, -1.231739572450155
, 0.001208650973866179
, -0.000005395239384953
]
ser :: Double
ser = 1.000000000190015
gammaln :: Double -> Double
gammaln xx =
let tmp_ = (xx + 5.5) - (xx + 0.5) * log (xx + 5.5)
ser_ = ser... |
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 ... | #Tcl | Tcl | package require Tcl 8.6
oo::class create GaltonBox {
variable b w h n x y cnt step dropping
constructor {BALLS {NUMPEGS 5} {HEIGHT 24}} {
set n $NUMPEGS
set w [expr {$n*2 + 1}]
set h $HEIGHT
puts -nonewline "\033\[H\033\[J"
set x [set y [lrepeat $BALLS 0]]
set cnt 0
set step 0
set dropping 1
set ... |
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... | #PL.2FM | PL/M | 100H: /* FIND SOME GAPFUL NUMBERS: NUMBERS DIVISIBLE BY 10F + L WHERE F IS */
/* THE FIRST DIGIT AND L IS THE LAST DIGIT */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
PR$CHAR: PROCEDURE( C ); DECLARE C BY... |
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
| #PARI.2FGP | PARI/GP | matsolve(A,B) |
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 ... | #Rust | Rust | use std::io;
use std::io::BufRead;
fn parse_entry(l: &str) -> (i32, String) {
let params: Vec<&str> = l.split(' ').collect();
let divisor = params[0].parse::<i32>().unwrap();
let word = params[1].to_string();
(divisor, word)
}
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock... |
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 ... | #Scala | Scala | $ scala GeneralFizzBuzz.scala
20
3 Fizz
5 Buzz
7 Baxx
^D
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
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... | #Logo | Logo | show map "char iseq 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... | #Lua | Lua | function getAlphabet ()
local letters = {}
for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end
return letters
end
local alpha = getAlphabet()
print(alpha[25] .. alpha[1] .. alpha[25]) |
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
| #PHP | PHP | <?php
echo "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... | #Ruby | Ruby | # This solution cheats and uses only one generator!
def powers(m)
return enum_for(__method__, m) unless block_given?
0.step{|n| yield n**m}
end
def squares_without_cubes
return enum_for(__method__) unless block_given?
cubes = powers(3)
c = cubes.next
powers(2) do |s|
c = cubes.next while c < s
... |
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... | #F.23 | F# | > let compose f g x = f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b |
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... | #Factor | Factor | ( scratchpad ) [ 2 * ] [ 1 + ] compose .
[ 2 * 1 + ]
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call .
9 |
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
| #jq | jq | # width and height define the outer dimensions;
# len defines the trunk size;
# scale defines the branch length relative to the trunk;
def main(width; height; len; scale):
def PI: (1|atan)*4;
def precision(n):
def pow(k): . as $in | reduce range(0;k) as $i (1; .*$in);
if . < 0 then - (-. | precision(n))... |
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
| #Julia | Julia |
const width = height = 1000.0
const trunklength = 400.0
const scalefactor = 0.6
const startingangle = 1.5 * pi
const deltaangle = 0.2 * pi
function tree(fh, x, y, len, theta)
if len >= 1.0
x2 = x + len * cos(theta)
y2 = y + len * sin(theta)
write(fh, "<line x1='$x' y1='$y' x2='$x2' y2='$y2' ... |
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... | #Julia | Julia | using Combinatorics
toi(set) = parse(Int, join(set, ""))
drop1(c, set) = toi(filter(x -> x != c, set))
function anomalouscancellingfractions(numdigits)
ret = Vector{Tuple{Int, Int, Int, Int, Int}}()
for nset in permutations(1:9, numdigits), dset in permutations(1:9, numdigits)
if nset < dset # only ... |
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
... | #Factor | Factor | USING: io kernel math math.functions math.parser multiline
prettyprint sequences splitting ;
IN: rosetta-code.fractran
STRING: fractran-string
17/91 78/85 19/51 23/38 29/33 77/29 95/23
77/19 1/17 11/13 13/11 15/14 15/2 55/1
;
: fractran-parse ( str -- seq )
" \n" split [ string>number ] map ;
: fractran-step ... |
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 ... | #Argile | Argile | use std
.: multiply <real a, real b> :. -> 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... | #Kotlin | Kotlin | // Version 1.3.21
fun fusc(n: Int): IntArray {
if (n <= 0) return intArrayOf()
if (n == 1) return intArrayOf(0)
val res = IntArray(n)
res[1] = 1
for (i in 2 until n) {
if (i % 2 == 0) {
res[i] = res[i / 2]
} else {
res[i] = res[(i - 1) / 2] + res[(i + 1) / 2... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every write(left(i := !10/10.0,5),gamma(.i))
end
procedure gamma(z) # Stirling's approximation
return (2*&pi/z)^0.5 * (z/&e)^z
end |
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 ... | #Wren | Wren | import "random" for Random
import "/trait" for Reversed
var boxW = 41 // Galton box width.
var boxH = 37 // Galton box height.
var pinsBaseW = 19 // Pins triangle base.
var nMaxBalls = 55 // Number of balls.
var centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1
var Rand = Random.new()
class C... |
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... | #PowerShell | PowerShell | function Get-FirstDigit {
param ( [int] $Number )
[int]$Number.ToString().Substring(0,1)
}
function Get-LastDigit {
param ( [int] $Number )
$Number % 10
}
function Get-BookendNumber {
param ( [Int] $Number )
10 * (Get-FirstDigit $Number) + (Get-LastDigit $Number)
}
function Test-Gapful {
param ( [In... |
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
| #Perl | Perl | use Math::Matrix;
my $a = Math::Matrix->new([0,1,0],
[0,0,1],
[2,0,1]);
my $b = Math::Matrix->new([1],
[2],
[4]);
my $x = $a->concat($b)->solve;
print $x; |
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 ... | #Sidef | Sidef | class FizzBuzz(schema=Hash(<3 Fizz 5 Buzz>...)) {
method filter(this) {
var fb = ''
schema.sort_by {|k,_| k.to_i }.each { |pair|
fb += (pair[0].to_i `divides` this ? pair[1] : '')
}
fb.len > 0 ? fb : this
}
}
func GeneralFizzBuzz(upto, schema) {
var ping = FizzB... |
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... | #M2000_Interpreter | M2000 Interpreter |
\\ old style Basic, including a Binary.Or() function
Module OldStyle {
10 LET A$=""
20 FOR I=ASC("A") TO ASC("Z")
30 LET A$=A$+CHR$(BINARY.OR(I, 32))
40 NEXT I
50 PRINT A$
}
CALL OldStyle
|
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... | #Maple | Maple | seq(StringTools:-Char(c), c = 97 .. 122); |
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
| #Picat | Picat | println("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... | #Rust | Rust | use std::cmp::Ordering;
use std::iter::Peekable;
fn powers(m: u32) -> impl Iterator<Item = u64> {
(0u64..).map(move |x| x.pow(m))
}
fn noncubic_squares() -> impl Iterator<Item = u64> {
NoncubicSquares {
squares: powers(2).peekable(),
cubes: powers(3).peekable(),
}
}
struct NoncubicSqua... |
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... | #Fantom | Fantom |
class Compose
{
static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2)
{
return |Obj x -> Obj| { fn2 (fn1 (x)) }
}
public static Void main ()
{
double := |Int x -> Int| { 2 * x }
|Int -> Int| quad := compose(double, double)
echo ("Double 3 = ${double(3)}")
echo ("Quadruple 3 ... |
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... | #Forth | Forth | : compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
r> compile,
postpone ;
;
' 2* ' 1+ compose ( xt )
3 swap execute . \ 7 |
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
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame
class FractalTree : JFrame("Fractal Tree") {
init {
background = Color.black
setBounds(100, 100, 800, 600)
isResizable = false
defaultCloseOperation = EXIT_ON_CLOSE
}
private fun d... |
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... | #Kotlin | Kotlin | fun indexOf(n: Int, s: IntArray): Int {
for (i_j in s.withIndex()) {
if (n == i_j.value) {
return i_j.index
}
}
return -1
}
fun getDigits(n: Int, le: Int, digits: IntArray): Boolean {
var mn = n
var mle = le
while (mn > 0) {
val r = mn % 10
if (r == ... |
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
... | #Fermat | Fermat | Func FT( arr, n, m ) =
;{executes John H. Conway's FRACTRAN language for a program stored in [arr], an}
;{input integer stored in n, for a maximum of m steps}
;{To allow the program to run indefinitely, give it negative or noninteger m}
exec:=1; {boolean to track whether the program need... |
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 ... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program functMul.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/***********************/
/* Initialized data */
/***********************/
.data
szRetourLigne: .asciz "\n"
szMessResult: .ascii "Resultat : " @ message result
sMessValeur: .fill 12,... |
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... | #Lua | Lua | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum ... |
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... | #J | J | 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 ... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic code declarations
define Balls = 80; \maximum number of balls
int Bx(Balls), By(Balls), \character cell coordinates of each ball
W, I, J, Peg, Dir;
[W:= Peek($40, $4A); \get screen width in characters
Clear; CrLf(6); CrLf(6);
for Peg:= 1... |
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 ... | #Yabasic | Yabasic | bola$ = "0000ff"
obst$ = "000000"
maxBalls = 10
cx = 1
cy = 2
dim Balls(maxBalls, 2)
open window 600,600
window origin "ct"
maxh = peek("winheight")
REM Draw the pins:
FOR row = 1 TO 7
FOR col = 1 TO row
FILL circle 40*col - 20*row, 40*row+80, 10
NEXT col
NEXT row
REM Animate
tick = 0
bolas = 0
colo... |
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... | #PureBasic | PureBasic | Procedure.b isGapNum(n.i)
n1.i=n%10
n2.i=Val(Left(Str(n),1))
If n%(n2*10+n1)=0
ProcedureReturn #True
Else
ProcedureReturn #False
EndIf
EndProcedure
Procedure PutGapNum(start.i,rep.i,lfi.i=10)
n.i=start
While rep
If isGapNum(n)
Print(Str(n)+" ")
rep-1
If rep%lfi=0 : PrintN... |
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
| #Phix | Phix | with javascript_semantics
function gauss_eliminate(sequence a, b)
{a, b} = deep_copy({a,b})
integer n = length(b)
atom tmp
for col=1 to n do
integer m = col
atom mx = a[m][m]
for i=col+1 to n do
tmp = abs(a[i][col])
if tmp>mx then
{m,mx} = ... |
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 ... | #Swift | Swift | import Foundation
print("Input max number: ", terminator: "")
guard let maxN = Int(readLine() ?? "0"), maxN > 0 else {
fatalError("Please input a number greater than 0")
}
func getFactor() -> (Int, String) {
print("Enter a factor and phrase: ", terminator: "")
guard let factor1Input = readLine() 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 ... | #Tailspin | Tailspin |
def input: {N: 110"1", words: [ { mod: 3"1", word: 'Fizz' }, { mod: 5"1", word: 'Buzz'}, {mod:7"1", word: 'Baxx'}]};
templates sayWords
def i: $;
templates maybeSay
def word: $.word;
$i mod $.mod -> \(<=0"1"> $word !\) !
end maybeSay
$input.words... -> maybeSay !
end sayWords
[ 1"1"..$input.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... | #Mathcad | Mathcad |
-- user-defined function that returns the ASCII code for string character ch.
code(ch):=str2vec(ch)[0
-- number of lower-case ASCII characters
N:=26
-- range variable covering the relative indices of the lower-case characters within the ASCII character set (0 = 'a', 25 = 'z').
k:=0..N-1
-- ASCII code for letter... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | start = 97;
lowerCaseLetters = Table[FromCharacterCode[start + i], {i, 0, 25}] |
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
| #PicoLisp | PicoLisp | (prinl "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... | #Scala | Scala | object Generators {
def main(args: Array[String]): Unit = {
def squares(n:Int=0):Stream[Int]=(n*n) #:: squares(n+1)
def cubes(n:Int=0):Stream[Int]=(n*n*n) #:: cubes(n+1)
def filtered(s:Stream[Int], c:Stream[Int]):Stream[Int]={
if(s.head>c.head) filtered(s, c.tail)
else if(s.head... |
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... | #Fortran | Fortran |
module functions_module
implicit none
private ! all by default
public :: f,g
contains
pure function f(x)
implicit none
real, intent(in) :: x
real :: f
f = sin(x)
end function f
pure function g(x)
implicit none
real, intent(in) :: x
real :: g
g ... |
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
| #Lambdatalk | Lambdatalk |
1) defining the function tree:
{def tree
{lambda {:e // last branch length
:s // trunks length
:k // ratio between two following branches
:a // rotate left
:b} // rotate right
{if {< :s :e}
then
else M:s T:a
{tree :e {* :k :s} :k :a :b}
... |
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... | #Lua | Lua | function indexOf(haystack, needle)
for idx,straw in pairs(haystack) do
if straw == needle then
return idx
end
end
return -1
end
function getDigits(n, le, digits)
while n > 0 do
local r = n % 10
if r == 0 or indexOf(digits, r) > 0 then
return fa... |
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
... | #Fortran | Fortran | C:\Nicky\RosettaCode\FRACTRAN\FRACTRAN.for(6) : Warning: This name has not been given an explicit type. [M]
INTEGER P(M),Q(M)!The terms of the fractions. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.