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/Four_is_magic | Four is magic | Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs... | #Swift | Swift | import Foundation
func fourIsMagic(_ number: NSNumber) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
formatter.locale = Locale(identifier: "en_EN")
var result: [String] = []
var numberString = formatter.string(from: number)!
result.append(numberString.capi... |
http://rosettacode.org/wiki/Four_is_magic | Four is magic | Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs... | #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
name_of() {
# return the English name for a numeric value
local -i n=$1
if (( n < 0 )); then
printf 'negative %s\n' "$(name_of $(( -n )))"
return 0
fi
# Names for numbers that fit in a bash integer
local -A names=([0]=zero [1]=one [2]=two [3]=three [4]=four [5]=five
... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #BCPL | BCPL | get "libhdr"
let width(n) = n<10 -> 1, 1 + width(n/10)
let floyd(rows) be
$( let maxno = rows * (rows+1)/2
let num = 1
for r = 1 to rows
$( for c = 1 to r
$( writed(num, 1 + width(maxno-rows+c))
num := num + 1
$)
wrch('*N')
$)
$)
let start() be
$( floyd(5)
... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Befunge | Befunge | 0" :seniL">:#,_&>:!#@_55+,:00p::1+*2/1v
vv+1:\-1p01g5-\g00<v`*9"o"\+`"c"\`9:::_
$>>\:::9`\"c"`+\9v:>>+00g1-:00p5p1-00g^
<v\*84-\g01+`*"o"<^<<p00:+1\+1/2*+1:::\
^>:#\1#,-#:\_$$.\:#^_$$>>1+\1-55+,:!#@_ |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Icon | Icon | #
# Floyd-Warshall algorithm.
#
# See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
#
record fw_results (n, distance, next_vertex)
link array
link numbers
link printf
procedure main ()
local example_graph
local fw
local u, v
example_graph := [[1, -2.0, 3],
... |
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 ... | #Raven | Raven | define multiply use a, b
a b * |
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 ... | #REALbasic | REALbasic |
Function Multiply(a As Integer, b As Integer) As Integer
Return a * b
End Function
|
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Lua | Lua | function dif(a, b, ...)
if(b) then return b-a, dif(b, ...) end
end
function dift(t) return {dif(unpack(t))} end
print(unpack(dift{1,3,6,10,15})) |
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
| #XSLT | XSLT | <xsl:text>Hello world!
</xsl:text> |
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
| #Yabasic | Yabasic |
print "Hello world!"
|
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #PicoLisp | PicoLisp | (pad 9 (format 7125 3))
(pad 9 (format 7125 3 ",")) # European format |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #PL.2FI | PL/I |
put edit (X) (p'999999.V999'); /* Western format. */
put edit (X) (p'999999,V999'); /* In European format. */
|
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #MATLAB_.2F_Octave | MATLAB / Octave | function [S,v] = fourBitAdder(input1,input2)
%Make sure that only 4-Bit numbers are being added. This assumes that
%if input1 and input2 are a vector of multiple decimal numbers, then
%the binary form of these vectors are an n by 4 matrix.
assert((size(input1,2) == 4) && (size(input2,2) == 4),'This wi... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #Arturo | Arturo | fivenum: function [lst][
lst: sort lst
m: (size lst)/2
lowerEnd: (odd? size lst)? -> m -> m-1
return @[
first lst
median slice lst 0 lowerEnd
median slice lst 0 dec size lst
median slice lst m dec size lst
last lst
]
]
lists: @[
@[15.0, 6.0, 42.0, 41.0... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #Common_Lisp | Common Lisp | (defvar *dims* '(10 10))
(defvar *prob-t* 0.5)
(defvar *prob-f* 0.1)
(defvar *prob-p* 0.01)
(defmacro with-gensyms (names &body body)
`(let ,(mapcar (lambda (n) (list n '(gensym))) names)
,@body))
(defmacro traverse-grid (grid rowvar colvar (&rest after-cols) &body body)
(with-gensyms (dims rows cols)
`(let*... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #BBC_BASIC | BBC BASIC | DIM @environ$(12)
@% = 4 : REM Column width
REM Initialise:
FOR E% = 1 TO 12
PROCsetenvironment(@environ$(E%))
seq% = E%
cnt% = 0
@environ$(E%) = FNgetenvironment
NEXT
REM Run hailstone sequences:
REPEAT
T% = 0
FOR E% = 1 TO 1... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Brat | Brat | array.prototype.flatten = {
true? my.empty?
{ [] }
{ true? my.first.array?
{ my.first.flatten + my.rest.flatten }
{ [my.first] + my.rest.flatten }
}
}
list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
p "List: #{list}"
p "Flattened: #{list.flatten}" |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #J | J | start=:3 :0
Moves=:0
N=:i.y
Board=: ?2$~,~y
'fr fc'=. (2,y)$}.#:(+?&.<:@<:)2x^2*y
End=: fr~:fc~:"1 Board
Board;End
)
abc=:'abcdefghij'
move=:3 :0
fc=. N e.abc i. y ([-.-.)abc
fr=. N e._-.~_ "."0 abc-.~":y
Board=: fr~:fc~:"1 Board
smoutput (":Moves=:Moves++/fr,fc),' moves'
if. Board-:End do.
... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Delphi | Delphi |
// First power of 2 that has specified leading decimal digits. Nigel Galloway: March 14th., 2021
let fG n g=let fN l=let l=10.0**(l-floor l) in l>=n && l<g in let f=log10 2.0 in seq{1..0x0FFFFFFF}|>Seq.filter(float>>(*)f>>fN)
printfn "p(23,1)->%d" (int(Seq.item 0 (fG 2.3 2.4)))
printfn "p(99,1)->%d" ... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Elena | Elena | import system'routines;
import extensions;
public program()
{
real x := 2.0r;
real xi := 0.5r;
real y := 4.0r;
real yi := 0.25r;
real z := x + y;
real zi := 1.0r / (x + y);
var numlist := new real[]{ x, y, z };
var numlisti := new real[]{ xi, yi, zi };
var multiplied := numlis... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Erlang | Erlang |
-module( first_class_functions_use_numbers ).
-export( [task/0] ).
task() ->
X = 2.0, Xi = 0.5, Y = 4.0, Yi = 0.25, Z = X + Y, Zi = 1.0 / (X + Y),
As = [X, Y, Z],
Bs = [Xi, Yi, Zi],
[io:fwrite( "Value: 2.5 Result: ~p~n", [(multiplier(A, B))(2.5)]) || {A, B} <- lists:zip(As, Bs)].
multiplier( N1, N2 ) ->... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Java | Java | switch (xx) {
case 1:
case 2:
/* 1 & 2 both come here... */
...
break;
case 4:
/* 4 comes here... */
...
break;
case 5:
/* 5 comes here... */
...
break;
default:
/* everything else */
break;
}
for (int i = 0; i < 10; ++i) {
...
if (some_condition) { break; }
... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #JavaScript | JavaScript | $ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4'
1
["DEBUG:",2]
4 |
http://rosettacode.org/wiki/Four_is_magic | Four is magic | Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs... | #Vlang | Vlang | import math
fn main() {
for n in [i64(0), 4, 6, 11, 13, 75, 100, 337, -164,
math.max_i64,
] {
println(four_is_magic(n))
}
}
fn four_is_magic(nn i64) string {
mut n := nn
mut s := say(n)
s = s[..1].to_upper() + s[1..]
mut t := s
for n != 4 {
n = i64(s.len)
s = say(n)
t += " is " + s + ", " + s... |
http://rosettacode.org/wiki/Four_is_magic | Four is magic | Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs... | #Wren | Wren | import "/str" for Str
var small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Bracmat | Bracmat | ( ( floyd
= lowerLeftCorner lastInColumn lastInRow row i W w
. put$(str$("Floyd " !arg ":\n"))
& !arg*(!arg+-1)*1/2+1
: ?lowerLeftCorner
: ?lastInColumn
& 1:?lastInRow:?row:?i
& whl
' ( !row:~>!arg
& @(!lastInColumn:? [?W)
... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #C | C | #include <stdio.h>
void t(int n)
{
int i, j, c, len;
i = n * (n - 1) / 2;
for (len = c = 1; c < i; c *= 10, len++);
c -= i; // c is the col where width changes
#define SPEED_MATTERS 0
#if SPEED_MATTERS // in case we really, really wanted to print huge triangles often
char tmp[32], s[4096], *p;
sprintf(tmp... |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #J | J | floyd=: verb define
for_j. i.#y do.
y=. y <. j ({"1 +/ {) y
end.
) |
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 ... | #REBOL | REBOL | multiply: func [a b][a * b] |
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 ... | #Relation | Relation |
function multiply(a,b)
set result = a*b
end function
|
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #M2000_Interpreter | M2000 Interpreter |
Form 80, 40
Module Forward_difference {
Print $(0,6) ' 6 characters column
Dim a(), b()
a()=(90,47,58,29,22,32,55,5,55,73)
Function Diff(a()) {
for i=0 to len(a())-2: a(i)=a(i+1)-a(i):Next i
Dim a(len(a())-1) ' redim one less
=a()
}
Print "Origi... |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | i={3,5,12,1,6,19,6,2,4,9};
Differences[i] |
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
| #Yorick | Yorick | write, "Hello world!" |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #Pop11 | Pop11 | ;;; field of length 12, 3 digits after decimal place
format_print('~12,3,0,`*,`0F', [1299.19]);
;;; prints "00001299.190"
format_print('~12,3,0,`*,`0F', [100000000000000000]);
;;; Since the number does not fit into the field prints "************"
;;; that is stars instead of the number
format_print('~12,3,0,`*,`0F', [-... |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #PowerShell | PowerShell | '{0:00000.000}' -f 7.125 |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #MUMPS | MUMPS | XOR(Y,Z) ;Uses logicals - i.e., 0 is false, anything else is true (1 is used if setting a value)
QUIT (Y&'Z)!('Y&Z)
HALF(W,X)
QUIT $$XOR(W,X)_"^"_(W&X)
FULL(U,V,CF)
NEW F1,F2
S F1=$$HALF(U,V)
S F2=$$HALF($P(F1,"^",1),CF)
QUIT $P(F2,"^",1)_"^"_($P(F1,"^",2)!($P(F2,"^",2)))
FOUR(Y,Z,C4)
NEW S,I,T
FOR I=4:-1:1 SET... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #C | C | #include <stdio.h>
#include <stdlib.h>
double median(double *x, int start, int end_inclusive) {
int size = end_inclusive - start + 1;
if (size <= 0) {
printf("Array slice cannot be empty\n");
exit(1);
}
int m = start + size / 2;
if (size % 2) return x[m];
return (x[m - 1] + x[m... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #ActionScript | ActionScript |
var cube:Function = function(x) {
return Math.pow(x, 3);
};
var cuberoot:Function = function(x) {
return Math.pow(x, 1/3);
};
function compose(f:Function, g:Function):Function {
return function(x:Number) {return f(g(x));};
}
var functions:Array = [Math.cos, Math.tan, cube];
var inverse:Array = [Math.acos, Math... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #D | D | import std.stdio, std.random, std.string, std.algorithm;
enum treeProb = 0.55; // Original tree probability.
enum fProb = 0.01; // Auto combustion probability.
enum cProb = 0.01; // Tree creation probability.
enum Cell : char { empty=' ', tree='T', fire='#' }
alias World = Cell[][];
bool hasBurningNeighbour... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #Bracmat | Bracmat | ( (environment=(cnt=0) (seq=))
& :?environments
& 13:?seq
& whl
' ( !seq+-1:>0:?seq
& new$environment:?env
& !seq:?(env..seq)
& !env !environments:?environments
)
& out$(Before !environments)
& whl
' ( !environments:? (=? (seq=>1) ?) ?
& !environments:?envs
& whl
' ( !envs:(=?en... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #C | C | #include <stdio.h>
#define JOBS 12
#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a))
typedef struct { int seq, cnt; } env_t;
env_t env[JOBS] = {{0, 0}};
int *seq, *cnt;
void hail()
{
printf("% 4d", *seq);
if (*seq == 1) return;
++*cnt;
*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / ... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Burlesque | Burlesque |
blsq ) {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}{\[}{)to{"Block"==}ay}w!
{1 2 3 4 5 6 7 8}
|
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Java | Java | import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class FlippingBitsGame extends JPanel {
final int maxLevel = 7;
final int minLevel = 3;
private Random rand = new Random();
private int[][] grid, target;
private Rectangle box;
private int n = maxLev... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #F.23 | F# |
// First power of 2 that has specified leading decimal digits. Nigel Galloway: March 14th., 2021
let fG n g=let fN l=let l=10.0**(l-floor l) in l>=n && l<g in let f=log10 2.0 in seq{1..0x0FFFFFFF}|>Seq.filter(float>>(*)f>>fN)
printfn "p(23,1)->%d" (int(Seq.item 0 (fG 2.3 2.4)))
printfn "p(99,1)->%d" ... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #F.23 | F# |
let x = 2.0
let xi = 0.5
let y = 4.0
let yi = 0.25
let z = x + y
let zi = 1.0 / ( x + y )
let multiplier (n1,n2) = fun (m:float) -> n1 * n2 * m
[x; y; z]
|> List.zip [xi; yi; zi]
|> List.map multiplier
|> List.map ((|>) 0.5)
|> printfn "%A"
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Factor | Factor | USING: arrays kernel literals math prettyprint sequences ;
IN: q
CONSTANT: x 2.0
CONSTANT: xi 0.5
CONSTANT: y 4.0
CONSTANT: yi .25
CONSTANT: z $[ $ x $ y + ]
CONSTANT: zi $[ 1 $ x $ y + / ]
CONSTANT: A ${ x y z }
CONSTANT: B ${ xi yi zi }
: multiplier ( n1 n2 -- q ) [ * * ] 2curry ;
: create-all ( seq1 seq2 --... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #jq | jq | $ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4'
1
["DEBUG:",2]
4 |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Julia | Julia |
function example()
println("Hello ")
@goto world
println("Never printed")
@label world
println("world")
end
|
http://rosettacode.org/wiki/Four_is_magic | Four is magic | Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs... | #zkl | zkl | fcn fourIsMagic(int){
if(int==0) return("Zero is four, four is magic.");
string:="";
while(1){ c:=nth(int,False);
string+="%s is ".fmt(c);
if(int = ( if(int==4) 0 else c.len() )){
string+="%s, ".fmt(nth(int,False));
}else{
string+="magic.";
break;
}
}
string[0].toUppe... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #C.23 | C# | using System;
using System.Text;
public class FloydsTriangle
{
internal static void Main(string[] args)
{
int count;
if (args.Length >= 1 && int.TryParse(args[0], out count) && count > 0)
{
Console.WriteLine(MakeTriangle(count));
}
else
{
... |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Java | Java | import static java.lang.String.format;
import java.util.Arrays;
public class FloydWarshall {
public static void main(String[] args) {
int[][] weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}};
int numVertices = 4;
floydWarshall(weights, numVertices);
}
stati... |
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 ... | #Retro | Retro | : multiply ( nn-n ) * ; |
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 ... | #REXX | REXX | multiply: return arg(1) * arg(2) /*return the product of the two arguments.*/ |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #MATLAB_.2F_Octave | MATLAB / Octave | Y = diff(X,n); |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Maxima | Maxima | ldiff(u, n) := block([m: length(u)], for j thru n do u: makelist(u[i + 1] - u[i], i, 1, m - j), u); |
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
| #Z80_Assembly | Z80 Assembly | org $4000
txt_output: equ $bb5a
push hl
ld hl,world
print: ld a,(hl)
cp 0
jr z,end
call txt_output
inc hl
jr print
end: pop hl
ret
world: defm "Hello world!\r\n\0" |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #PureBasic | PureBasic | RSet(StrF(7.125,3),8,"0") ; Will be 0007.125 |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #Python | Python | from math import pi, exp
r = exp(pi)-pi
print r
print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r)
print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r)... |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #MyHDL | MyHDL | """
To run:
python3 Four_bit_adder_011.py
"""
from myhdl import *
# define set of primitives
@block
def NOTgate( a, q ): # define component name & interface
""" q <- not(a) """
@always_comb # define asynchronous logic
def NOTgateLogic():
q.next = not a
return NOTgateLogic # ... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Fivenum {
public static class Helper {
public static string AsString<T>(this ICollection<T> c, string format = "{0}") {
StringBuilder sb = new StringBuilder("[");
int count = 0;
... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Ada | Ada | with Ada.Float_Text_IO,
Ada.Integer_Text_IO,
Ada.Text_IO,
Ada.Numerics.Elementary_Functions;
procedure First_Class_Functions is
use Ada.Float_Text_IO,
Ada.Integer_Text_IO,
Ada.Text_IO,
Ada.Numerics.Elementary_Functions;
function Sqr (X : Float) return Float is
begin
... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | #chance of empty->tree
set :p 0.004
#chance of spontaneous tree combustion
set :f 0.001
#chance of tree in initial state
set :s 0.5
#height of world
set :H 10
#width of world
set :W 20
has-burning-neigbour state pos:
for i range -- swap ++ dup &< pos:
for j range -- swap ++ dup &> pos:
& i j
try:
state!
... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #Clojure | Clojure |
(def hailstone-src
"(defn hailstone-step [env]
(let [{:keys[n cnt]} env]
(cond
(= n 1) {:n 1 :cnt cnt}
(even? n) {:n (/ n 2) :cnt (inc cnt)}
:else {:n (inc (* n 3)) :cnt (inc cnt)})))")
(defn create-hailstone-table [f-src]
(let [done? (fn [e] (= (:n e) 1))
... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #D | D | import std.stdio, std.algorithm, std.range, std.array;
struct Prop {
int[string] data;
ref opDispatch(string s)() pure nothrow {
return data[s];
}
}
immutable code = `
writef("% 4d", e.seq);
if (e.seq != 1) {
e.cnt++;
e.seq = (e.seq & 1) ? 3 * e.seq + 1 : e.seq / 2;
}`;
void main() {
... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list_t list_t, *list;
struct list_t{
int is_list, ival; /* ival is either the integer value or list length */
list *lst;
};
list new_list()
{
list x = malloc(sizeof(list_t));
x->ival = 0;
x->is_list = 1;
x->lst = 0;
return x;
}
void ... |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #JavaScript | JavaScript | function numOfRows(board) { return board.length; }
function numOfCols(board) { return board[0].length; }
function boardToString(board) {
// First the top-header
var header = ' ';
for (var c = 0; c < numOfCols(board); c++)
header += c + ' ';
// Then the side-header + board
var sideboard =... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Factor | Factor | USING: formatting fry generalizations kernel literals math
math.functions math.parser sequences tools.time ;
CONSTANT: ld10 $[ 2 log 10 log / ]
: p ( L n -- m )
swap [ 0 0 ]
[ '[ over _ >= ] ]
[ [ log10 >integer 10^ ] keep ] tri*
'[
1 + dup ld10 * dup >integer - 10 log * e^ _ * truncate
... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #FreeBASIC | FreeBASIC | #define FAC 0.30102999566398119521373889472449302677
function p( L as uinteger, n as uinteger ) as uinteger
dim as uinteger count, j = 0
dim as double x, y
dim as string digits, LS = str(L)
while count < n
j+=1
x = FAC * j
if x < len(LS) then continue while
y = 10^(x-in... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Fantom | Fantom |
class Main
{
static |Float -> Float| combine (Float n1, Float n2)
{
return |Float m -> Float| { n1 * n2 * m }
}
public static Void main ()
{
Float x := 2f
Float xi := 0.5f
Float y := 4f
Float yi := 0.25f
Float z := x + y
Float zi := 1 / (x + y)
echo (combine(x, xi)(0.5f))
... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Go | Go | package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
// point A
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
// point B
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
for (i in 0 .. 2) {
for (j in 0 .. 2) {
if (i + j == 2) continue
if (i + j == 3) break
println(i + j)
}
}
println()
if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments shou... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Lua | Lua | i = 0
while true do
i = i + 1
if i > 10 then break end
end |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #C.2B.2B | C++ |
#include <windows.h>
#include <sstream>
#include <iostream>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
class floyds_tri
{
public:
... |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #JavaScript | JavaScript | var graph = [];
for (i = 0; i < 10; ++i) {
graph.push([]);
for (j = 0; j < 10; ++j)
graph[i].push(i == j ? 0 : 9999999);
}
for (i = 1; i < 10; ++i) {
graph[0][i] = graph[i][0] = parseInt(Math.random() * 9 + 1);
}
for (k = 0; k < 10; ++k) {
for (i = 0; i < 10; ++i) {
for (j = 0; j < 10; ++j) {
... |
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 ... | #Ring | Ring |
func multiply x,y return x*y
|
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 ... | #RLaB | RLaB | >> class(sin)
function
>> type(sin)
builtin |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #NetRexx | NetRexx | /* NetRexx*************************************************************
* Forward differences
* 18.08.2012 Walter Pachl derived from Rexx
**********************************************************************/
Loop n=-1 To 11
differences('90 47 58 29 22 32 55 5 55 73',n)
End
method differences(a,n) publi... |
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
| #zkl | zkl | println("Hello world!"); |
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
| #Zig | Zig | const std = @import("std");
pub fn main() !void {
try std.io.getStdOut().writer().writeAll("Hello world!\n");
} |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #R | R | > sprintf("%f", pi)
[1] "3.141593"
> sprintf("%.3f", pi)
[1] "3.142"
> sprintf("%1.0f", pi)
[1] "3"
> sprintf("%5.1f", pi)
[1] " 3.1"
> sprintf("%05.1f", pi)
[1] "003.1"
> sprintf("%+f", pi)
[1] "+3.141593"
> sprintf("% f", pi)
[1] " 3.141593"
> sprintf("%-10f", pi)# left justified
[1] "3.141593 "
> sprintf("%e", pi)... |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #Racket | Racket |
-> (displayln (~a 7.125 #:width 9 #:align 'right #:pad-string "0"))
00007.125
|
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Nim | Nim | type
Bools[N: static int] = array[N, bool]
SumCarry = tuple[sum, carry: bool]
proc ha(a, b: bool): SumCarry = (a xor b, a and b)
proc fa(a, b, ci: bool): SumCarry =
let a = ha(ci, a)
let b = ha(a[0], b)
result = (b[0], a[1] or b[1])
proc fa4(a, b: Bools[4]): Bools[5] =
var co, s: Bools[4]
for i in... |
http://rosettacode.org/wiki/Fivenum | Fivenum | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language i... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
/////////////////////////////////////////////////////////////////////////////
// The following is taken from https://cpplove.blogspot.com/2012/07/printing-tuples.html
// Define a type which holds an unsigned integer value
template<std::s... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #11l | 11l | L(i) 1..100
I i % 15 == 0
print(‘FizzBuzz’)
E I i % 3 == 0
print(‘Fizz’)
E I i % 5 == 0
print(‘Buzz’)
E
print(i) |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #360_Assembly | 360 Assembly | * Five weekends 31/05/2016
FIVEWEEK CSECT
USING FIVEWEEK,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
... |
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits | First perfect square in base n with n unique digits | Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do ... | #11l | 11l | L(base) 2..16
V n = Int64(Float(base) ^ ((base - 1) / 2))
L
V sq = n * n
V sqstr = String(sq, radix' base)
I sqstr.len >= base & Set(Array(sqstr)).len == base
V nstr = String(n, radix' base)
print(‘Base #2: #8^2 = #.’.format(base, nstr, sqstr))
L.break
n++ |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Aikido | Aikido |
import math
function compose (f, g) {
return function (x) { return f(g(x)) }
}
var fn = [Math.sin, Math.cos, function(x) { return x*x*x }]
var inv = [Math.asin, Math.acos, function(x) { return Math.pow(x, 1.0/3) }]
for (var i=0; i<3; i++) {
var f = compose(inv[i], fn[i])
println(f(0.5)) // 0.5
}... |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #ALGOL_68 | ALGOL 68 | MODE F = PROC (REAL)REAL;
OP ** = (REAL x, power)REAL: exp(ln(x)*power);
# Add a user defined function and its inverse #
PROC cube = (REAL x)REAL: x * x * x;
PROC cube root = (REAL x)REAL: x ** (1/3);
# First class functions allow run-time creation of functions from functions #
# return function compose(f,g)(x) == ... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #EasyLang | EasyLang | p_fire = 0.00002
p_tree = 0.002
#
len f[] 102 * 102
len p[] len f[]
background 100
clear
for r range 100
for c range 100
i = r * 102 + c + 103
if randomf < 0.5
f[i] = 1
.
.
.
timer 0
#
subr show
for r range 100
for c range 100
i = r * 102 + c + 103
h = f[i]
if h <> p[i]
... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #EchoLisp | EchoLisp |
(define (bump-value)
(when (> value 1)
(set! count (1+ count))
(set! value (if (even? value) (/ value 2) (1+ (* 3 value))))))
(define (env-show name envs )
(write name)
(for ((env envs)) (write (format "%4a" (eval name env))))
(writeln))
(define (task (envnum 12))
(define envs (for/list ((i envnum)) (environ... |
http://rosettacode.org/wiki/First_class_environments | First class environments | According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable".
Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "... | #Erlang | Erlang | Note that using the Process Dictionary:
Destroys referencial transparency
Makes debugging difficult
Survives Catch/Throw
|
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #C.23 | C# |
using System;
using System.Collections;
using System.Linq;
namespace RosettaCodeTasks
{
static class FlattenList
{
public static ArrayList Flatten(this ArrayList List)
{
ArrayList NewList = new ArrayList ( );
NewList.AddRange ( List );
while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 )
{
... |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Julia | Julia | module FlippingBitsGame
using Printf, Random
import Base.size, Base.show, Base.==
struct Configuration
M::BitMatrix
end
Base.size(c::Configuration) = size(c.M)
function Base.show(io::IO, conf::Configuration)
M = conf.M
nrow, ncol = size(M)
print(io, " " ^ 3)
for c in 1:ncol
@printf(io,... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Go | Go | package main
import (
"fmt"
"math"
"time"
)
const ld10 = math.Ln2 / math.Ln10
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func p(L, n uint64) uint64 {
i := L
digit... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Groovy | Groovy | def multiplier = { n1, n2 -> { m -> n1 * n2 * m } }
def ε = 0.00000001 // tolerance(epsilon): acceptable level of "wrongness" to account for rounding error
[(2.0):0.5, (4.0):0.25, (6.0):(1/6.0)].each { num, inv ->
def new_function = multiplier(num, inv)
(1.0..5.0).each { trial ->
assert (new_function... |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Haskell | Haskell | module Main
where
import Text.Printf
-- Pseudo code happens to be valid Haskell
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
-- Multiplier function
multiplier :: Double -> Double -> Double -> Double
multiplier a b = \m -> a * b * m
main :: IO ()
main = do
let
numbers = [x, y, z]
... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
try
% do some stuff
catch
% in case of error, continue here
end
|
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #MATLAB_.2F_Octave | MATLAB / Octave |
try
% do some stuff
catch
% in case of error, continue here
end
|
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #Clojure | Clojure |
(defn TriangleList [n]
(let [l (map inc (range))]
(loop [l l x 1 nl []]
(if (= n (count nl))
nl
(recur (drop x l) (inc x) (conj nl (take x l)))))))
(defn TrianglePrint [n]
(let [t (TriangleList n)
m (count (str (last (last t))))
f (map #(map str %) t)
l (map #(m... |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #jq | jq |
def weights: {
"1": {"3": -2},
"2": {"1" : 4, "3": 3},
"3": {"4": 2},
"4": {"2": -1}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.