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/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... | #BBC_BASIC | BBC BASIC | GOSUB subroutine
(loop)
PRINT "Infinite loop"
GOTO loop
END
(subroutine)
PRINT "In subroutine"
WAIT 100
RETURN |
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... | #Bracmat | Bracmat | ( LOOP
= out$"Hi again!"
& !LOOP
)
& out$Hi!
& !LOOP |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | magic[num_] := Capitalize[ StringRiffle[ Partition[
FixedPointList[IntegerName[StringLength[#], "Cardinal"] &, IntegerName[num, "Cardinal"]],
2, 1] /. {n_, n_} :> {n, "magic"}, ", ", " is "] <> "."] |
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... | #Nim | Nim | import strutils
const
Small = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
Tens = ["", "", "t... |
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... | #360_Assembly | 360 Assembly | * Floyd's triangle 21/06/2018
FLOYDTRI PROLOG
L R5,NN nn
BCTR R5,0 -1
M R4,NN nn*(nn-1)
SRA R5,1 /2
A R5,NN m=(nn*(nn-1))/2+nn; max_value
CVD R5,XDEC ... |
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... | #Action.21 | Action! | PROC Triangle(BYTE level)
INT v,i
BYTE x,y
BYTE ARRAY widths(20)
CHAR ARRAY tmp(5)
v=1
FOR y=1 TO level-1
DO
v==+y
OD
FOR x=0 TO level-1
DO
StrI(v+x,tmp)
widths(x)=tmp(0)
OD
v=1
FOR y=1 TO level
DO
FOR x=0 TO y-1
DO
StrI(v,tmp)
FOR i=tmp(0) TO widths(x)-1
... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #J | J | _80 ]\ fread 'flr-infile.dat' NB. reads the file into a n by 80 array
_80 |.\ fread 'flr-infile.dat' NB. as above but reverses each 80 byte chunk
'flr-outfile.dat' fwrite~ , _80 |.\ fread 'flr-infile.dat' NB. as above but writes result to file (720 bytes)
processFixLenFile=: fwrite~ [: , _80 |.\ fread ... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #jq | jq | jq -Rrs -f program.jq infile.dat
|
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Julia | Julia |
function processfixedlengthrecords(infname, blocksize, outfname)
inf = open(infname)
outf = open(outfname, "w")
filedata = [ read(inf, blocksize) for _ in 1:10 ]
for line in filedata
s = join([Char(c) for c in line], "")
@assert(length(s) == blocksize)
write(outf, s)
end
... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Lua | Lua | -- prep: convert given sample text to fixed length "infile.dat"
local sample = [[
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 ... |
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 ... | #Common_Lisp | Common Lisp | #!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#
(progn ;;init forms
(ros:ensure-asdf)
#+quicklisp(ql:quickload '() :silent t)
)
(defpackage :ros.script.floyd-warshall.3861181636
(:use :cl))
(in-package :ros.script.floyd-warshall.3861181636)
;;;
;;; Floyd-Warshall algorithm.
;;;
;;; See https://... |
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 ... | #PL.2FSQL | PL/SQL | FUNCTION multiply(p_arg1 NUMBER, p_arg2 NUMBER) RETURN NUMBER
IS
v_product NUMBER;
BEGIN
v_product := p_arg1 * p_arg2;
RETURN v_product;
END; |
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... | #Haskell | Haskell | forwardDifference :: Num a => [a] -> [a]
forwardDifference = tail >>= zipWith (-)
nthForwardDifference :: Num a => [a] -> Int -> [a]
nthForwardDifference = (!!) . iterate forwardDifference
main :: IO ()
main =
mapM_ print $
take 10 (iterate forwardDifference [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]) |
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
| #Wisp | Wisp | import : scheme base
scheme write
display "Hello world!"
newline |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | StringTake["000000" <> ToString[7.125], -9]
00007.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.
| #MATLAB_.2F_Octave | MATLAB / Octave | >> disp(sprintf('%09.3f',7.125))
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 ... | #JavaScript | JavaScript |
function acceptedBinFormat(bin) {
if (bin == 1 || bin === 0 || bin === '0')
return true;
else
return bin;
}
function arePseudoBin() {
var args = [].slice.call(arguments), len = args.length;
while(len--)
if (acceptedBinFormat(args[len]) !== true)
throw new Error('a... |
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... | #ALGOL_68 | ALGOL 68 | LONG REAL tree prob = 0.55, # original tree probability #
f prob = 0.01, # new combustion probability #
p prob = 0.01; # tree creation probability #
MODE CELL = CHAR; CELL empty=" ", tree="T", burning="#";
MODE WORLD = [6, 65]CELL;
PROC has burning neighbours = (WORLD world, INT r, c)BOOL:(
... |
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
| #Aime | Aime | void
show_list(list l)
{
integer i, k;
o_text("[");
i = 0;
while (i < ~l) {
o_text(i ? ", " : "");
if (l_j_integer(k, l, i)) {
o_integer(k);
} else {
show_list(l[i]);
}
i += 1;
}
o_text("]");
}
list
flatten(list c, object o)... |
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 ... | #APL | APL | #!/usr/local/bin/apl -s --
∇r←b FlipRow ix ⍝ Flip a row
r←b
r[ix;]←~r[ix;]
∇
∇r←b FlipCol ix ⍝ Flip a column
r←b
r[;ix]←~r[;ix]
∇
∇r←RandFlip b;ix ⍝ Flip a random row or column
ix←?↑⍴b
→(2|?2)/col
r←b FlipRow ix ⋄ →0
col: ... |
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 ... | #AutoHotkey | AutoHotkey | size := 3 ; max 26
Gui, Add, Button, , O
Loop, %size%
{
x := chr(A_Index+64)
If x = A
Loop, %size%
Gui, Add, Button, y+4 gFlip, % A_Index
Gui, Add, Button, ym gFlip, % x
Loop, %size%
{
y := A_Index
Random, %x%%y%, 0, 1
Gui, Add, Edit, v%x%%y% ReadOnly, % %x%%y%
}
}
Gui, Add, Text, ym, Moves:`nTarget:
L... |
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... | #C | C | int main()
{
int i,j;
for (j=1; j<1000; j++) {
for (i=0; i<j, i++) {
if (exit_early())
goto out;
/* etc. */
}
}
out:
return 0;
} |
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... | #C.23 | C# | int GetNumber() {
return 5;
} |
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... | #Perl | Perl | use Lingua::EN::Numbers qw(num2en);
sub cardinal {
my($n) = @_;
(my $en = num2en($n)) =~ s/\ and|,//g;
$en;
}
sub magic {
my($int) = @_;
my $str;
while () {
$str .= cardinal($int) . " is ";
if ($int == 4) {
$str .= "magic.\n";
last
} else {
... |
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... | #Ada | Ada |
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line;
procedure Floyd_Triangle is
rows : constant Natural := Natural'Value(Ada.Command_Line.Argument(1));
begin
for r in 1..rows loop
for i in 1..r loop
Ada.Integer_Text_IO.put (r*(r-1)/2+i, Width=> Natural'Image(rows*(rows-1)/2+i)'Length);
end ... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #M2000_Interpreter | M2000 Interpreter |
Module FixedFile {
Read fixed$
OldLocale=Locale
\\ chr$(string_argument$)
\\ use Locale to convert from Ansi to Utf-16LE
\\ Read Ansi form files also use Locale
Locale 1032
Try ok {
\\ Make the file first
Const Center=2
Font "Courier New"
... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
FixedRecordReverse[inFile_File, outFile_File, length_ : 80] :=
Module[{inStream, outStream, line, byte},
WithCleanup[
inStream = OpenRead[inFile, BinaryFormat -> True];
outStream = OpenWrite[outFile, BinaryFormat -> True];
,
While[True,
line = {};
Do[
byte = Binar... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Neko | Neko | /**
fixed length records, in Neko
*/
var LRECL = 80
var reverse = function(s) {
var len = $ssize(s)
if len < 2 return s
var reverse = $smake(len)
var pos = 0
while len > 0 $sset(reverse, pos ++= 1, $sget(s, len -= 1))
return reverse
}
var file_open = $loader.loadprim("std@file_open", 2)
var file_re... |
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 ... | #D | D | import std.stdio;
void main() {
int[][] weights = [
[1, 3, -2],
[2, 1, 4],
[2, 3, 3],
[3, 4, 2],
[4, 2, -1]
];
int numVertices = 4;
floydWarshall(weights, numVertices);
}
void floydWarshall(int[][] weights, int numVertices) {
import std.array;
real... |
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 ... | #Plain_English | Plain English | To multiply a number with another number:
Multiply the number by the other number. |
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 ... | #Pop11 | Pop11 | define multiply(a, b);
a * b
enddefine; |
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... | #HicEst | HicEst | REAL :: n=10, list(n)
list = ( 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 )
WRITE(Format='i1, (i6)') 0, list
DO i = 1, n-1
ALIAS(list,1, diff,n-i) ! rename list(1 ... n-i) with diff
diff = list($+1) - diff ! $ is the running left hand array index
WRITE(Format='i1, (i6)') i, diff
ENDDO
END |
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
| #Wolfram_Language | Wolfram Language | 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.
| #Mercury | Mercury |
:- module formatted_numeric_output.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string.
main(!IO) :-
io.format("%09.3f\n", [f(7.125)], !IO).
|
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.
| #min | min | (quote cons "" join) :str-append
(pick length - repeat swap str-append) :left-pad
7.125 string "0" 9 left-pad puts! |
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 ... | #jq | jq | # Start with the 'not' and 'and' building blocks.
# These allow us to construct 'nand', 'or', and 'xor',
# and so on.
def bit_not: if . == 1 then 0 else 1 end;
def bit_and(a; b): if a == 1 and b == 1 then 1 else 0 end;
def bit_nand(a; b): bit_and(a; b) | bit_not;
def bit_or(a; b): bit_nand(bit_nand(a;a); bit_na... |
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... | #AutoHotkey | AutoHotkey |
; The array Frame1%x%_%y% holds the current frame. frame2%x%_%y%
; is then calculated from this, and printed. frame2 is then copied to frame1.
; Two arrays are necessary so that each cell advances at the same time
; T=Tree, #=Fire, O=Empty cell
; Size holds the width and height of the map and is used as the # of iter... |
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
| #ALGOL_68 | ALGOL 68 | main:(
[][][]INT list = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ());
print((list, new line))
) |
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 ... | #BASIC | BASIC | 10 DEFINT A-Z
20 PRINT "*** FLIP THE BITS ***"
30 INPUT "Board size";S
40 IF S<3 OR S>8 THEN PRINT "3 <= size <= 8": GOTO 30
50 RANDOMIZE
60 DIM B(S,S),G(S,S)
70 FOR X=1 TO S
80 FOR Y=1 TO S
90 B=INT(.5+RND(1))
100 B(X,Y)=B: G(X,Y)=B
110 NEXT Y,X
120 FOR A=0 TO 10+2*INT(10*RND(1))
130 R=INT(.5+RND(1))
140 N=1+INT(S*RND... |
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... | #C.2B.2B | C++ | #include <iostream>
int main()
{
LOOP:
std::cout << "Hello, World!\n";
goto LOOP;
} |
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... | #COBOL | COBOL | PROGRAM-ID. Go-To-Example.
PROCEDURE DIVISION.
Foo.
DISPLAY "Just a reminder: GO TOs are evil."
GO TO Foo
. |
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... | #Phix | Phix | with javascript_semantics
--<adapted from demo\rosetta\number_names.exw, which alas outputs ",", "and", uses "minus" instead of "negative", etc...>
constant twenties = {"zero","one","two","three","four","five","six","seven","eight","nine","ten",
"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen... |
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... | #ALGOL_68 | ALGOL 68 | # procedure to print a Floyd's Triangle with n lines #
PROC floyds triangle = ( INT n )VOID:
BEGIN
# calculate the number of the highest number that will be printed #
# ( the sum of the integers 1, 2, ... n ) #
INT max number = ( n * ( n + 1 ) ) OVER 2;... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Nim | Nim | import algorithm
proc reverse(infile, outfile: string) =
let input = infile.open(fmRead)
defer: input.close()
let output = outfile.open(fmWrite)
defer: output.close()
var buffer: array[80, byte]
while not input.endOfFile:
let countRead = input.readBytes(buffer, 0, 80)
if countRead < 80:
... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Pascal | Pascal | program reverseFixedLines(input, output, stdErr);
const
lineLength = 80;
var
// in Pascal, `string[n]` is virtually an alias for `array[1..n] of char`
line: string[lineLength];
i: integer;
begin
while not eof() do
begin
for i := 1 to lineLength do
begin
read(line[i]);
end;
for i := lineLength downto ... |
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 ... | #EchoLisp | EchoLisp |
(lib 'matrix)
;; in : initialized dist and next matrices
;; out : dist and next matrices
;; O(n^3)
(define (floyd-with-path n dist next (d 0))
(for* ((k n) (i n) (j n))
#:break (< (array-ref dist j j) 0) => 'negative-cycle
(set! d (+ (array-ref dist i k) (array-ref dist k j)))
(when (< d (array-... |
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 ... | #PostScript | PostScript | 3 4 mul |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(A) # Compute all forward difference orders for argument list
every order := 1 to (*A-1) do showList(order, fdiff(A, order))
end
procedure fdiff(A, order)
every 1 to order do {
every put(B := [], A[i := 2 to *A] - A[i-1])
A := B
}
return A
end
procedure showList(o... |
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
| #Wren | Wren | System.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.
| #Modula-3 | Modula-3 | IO.Put(Fmt.Pad("7.125\n", length := 10, padChar := '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.
| #Nanoquery | Nanoquery | printer = 7.125
println format("%09.3f", printer) |
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 ... | #Jsish | Jsish | #!/usr/bin/env jsish
/* 4 bit adder simulation, in Jsish */
function not(a) { return a == 1 ? 0 : 1; }
function and(a, b) { return a + b < 2 ? 0 : 1; }
function nand(a, b) { return not(and(a, b)); }
function or(a, b) { return nand(nand(a,a), nand(b,b)); }
function xor(a, b) { return nand(nand(nand(a,b), a), nand(nand(a... |
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... | #BASIC | BASIC | N = 150 : M = 150 : P = 0.03 : F = 0.00003
dim f(N+2,M+2) # 1 tree, 0 empty, 2 fire
dim fn(N+2,M+2)
graphsize N,M
fastgraphics
for x = 1 to N
for y = 1 to M
if rand<0.5 then f[x,y] = 1
next y
next x
while True
for x = 1 to N
for y = 1 to M
if not f[x,y] and rand<P then fn[x,y]=1
if f[x,y]=2 then fn[... |
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
| #APL | APL | ∊ |
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 ... | #BCPL | BCPL | get "libhdr"
static $( randstate = ? $)
let rand() = valof
$( randstate := random(randstate)
resultis randstate >> 7
$)
let showboard(size, board, goal) be
$( writes(" == BOARD == ")
for i=1 to 19 do wrch(' ')
writes(" == GOAL ==*N")
for i=1 to 2
$( writes(" ")
for j=1 to size do ... |
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 ... | #C | C |
#include <stdio.h>
#include <stdlib.h>
int i, j;
void fliprow(int **b, int sz, int n)
{
for(i = 0; i < sz; i++)
b[n+1][i] = !b[n+1][i];
}
void flipcol(int **b, int sz, int n)
{
for(i = 1; i <= sz; i++)
b[i][n] = !b[i][n];
}
void initt(int **t, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++... |
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... | #Comal | Comal | myprocedure
END // End of main program
PROC myprocedure
PRINT "Hello, this is a procedure"
ENDPROC myprocedure |
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... | #D | D | import std.stdio;
void main() {
label1:
writeln("I'm in your infinite loop.");
goto label1;
} |
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... | #Python | Python | import random
from collections import OrderedDict
numbers = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
1... |
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... | #ALGOL_W | ALGOL W | begin
% prints a Floyd's Triangle with n lines %
procedure floydsTriangle ( integer value n ) ;
begin
% the triangle should be left aligned with the individual numbers %
% right-aligned with only one space before the number in the final %
% row... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Perl | Perl | open $in, '<', 'flr-infile.dat';
open $out, '>', 'flr-outfile.dat';
while ($n=sysread($in, $record, 80)) { # read in fixed sized binary chunks
syswrite $out, reverse $record; # write reversed records to file
print reverse($record)."\n" # display reversed records, line-by-line
}
close $out; |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Phix | Phix | without js -- file i/o
constant sample_text = """
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 ... |
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 ... | #Elixir | Elixir | defmodule Floyd_Warshall do
def main(n, edge) do
{dist, next} = setup(n, edge)
{dist, next} = shortest_path(n, dist, next)
print(n, dist, next)
end
defp setup(n, edge) do
big = 1.0e300
dist = for i <- 1..n, j <- 1..n, into: %{}, do: {{i,j},(if i==j, do: 0, else: big)}
next = for i <- 1..... |
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 ... | #PowerShell | PowerShell | function multiply {
return $args[0] * $args[1]
} |
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... | #IDL | IDL | print,(x = randomu(seed,8)*100)
15.1473 58.0953 82.7465 16.8637 97.7182 59.7856 17.7699 74.9154
print,ts_diff(x,1)
-42.9479 -24.6513 65.8828 -80.8545 37.9326 42.0157 -57.1455 0.000000
print,ts_diff(x,2)
-18.2967 -90.5341 146.737 ... |
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
| #X10 | X10 | class HelloWorld {
public static def main(args:Rail[String]):void {
if (args.size < 1) {
Console.OUT.println("Hello world!");
return;
}
}
} |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
import java.text.MessageFormat
sevenPointOneTwoFive = double 7.125
-- using NetRexx Built-In Functions (BIFs)
say Rexx(sevenPointOneTwoFive).format(5, 3).changestr(' ', '0')
-- using Java library constructs
System.out.printf('%... |
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.
| #Nim | Nim | import strformat
const r = 7.125
echo r
echo fmt"{-r:9.3f}"
echo fmt"{r:9.3f}"
echo fmt"{-r:09.3f}"
echo fmt"{r:09.3f}" |
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 ... | #Julia | Julia | using Printf
xor{T<:Bool}(a::T, b::T) = (a&~b)|(~a&b)
halfadder{T<:Bool}(a::T, b::T) = (xor(a,b), a&b)
function fulladder{T<:Bool}(a::T, b::T, c::T=false)
(s, ca) = halfadder(c, a)
(s, cb) = halfadder(s, b)
(s, ca|cb)
end
function adder(a::BitArray{1}, b::BitArray{1}, c0::Bool=false)
len = lengt... |
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... | #Batch_File | Batch File | m - length and width of the array
p - probability of a tree growing
f - probability of a tree catching on fire
i - iterations to output
|
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
| #AppleScript | AppleScript | my_flatten({{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}})
on my_flatten(aList)
if class of aList is not list then
return {aList}
else if length of aList is 0 then
return aList
else
return my_flatten(first item of aList) & (my_flatten(rest of aList))
end if
end my_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 ... | #C.2B.2B | C++ |
#include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() ... |
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... | #11l | 11l | V (x, xi, y, yi) = (2.0, 0.5, 4.0, 0.25)
V z = x + y
V zi = 1.0 / (x + y)
V multiplier = (n1, n2) -> (m -> @=n1 * @=n2 * m)
V numlist = [x, y, z]
V numlisti = [xi, yi, zi]
print(zip(numlist, numlisti).map((n, inversen) -> multiplier(inversen, n)(.5))) |
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... | #E | E | escape ej {
...body...
}
|
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... | #q | q | C:``one`two`three`four`five`six`seven`eight`nine`ten,
`eleven`twelve`thirteen`fourteen`fifteen`sixteen`seventeen`eighteen`nineteen / cardinal numbers <20
T:``ten`twenty`thirty`forty`fifty`sixty`seventy`eighty`ninety / tens
M:``thousand`million... |
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... | #AppleScript | AppleScript | -- FLOYDs TRIANGLE -----------------------------------------------------------
-- floyd :: Int -> [[Int]]
on floyd(n)
script floydRow
on |λ|(start, row)
{start + row + 1, enumFromTo(start, start + row)}
end |λ|
end script
snd(mapAccumL(floydRow, 1, enumFromTo(0, n - 1)))
end ... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Python | Python |
infile = open('infile.dat', 'rb')
outfile = open('outfile.dat', 'wb')
while True:
onerecord = infile.read(80)
if len(onerecord) < 80:
break
onerecordreversed = bytes(reversed(onerecord))
outfile.write(onerecordreversed)
infile.close()
outfile.close()
|
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #Raku | Raku | $*OUT = './flr-outfile.dat'.IO.open(:w, :bin) orelse .die; # open a file in binary mode for writing
while my $record = $*IN.read(80) { # read in fixed sized binary chunks
$*OUT.write: $record.=reverse; # write reversed records out to $outfile
$*ERR.say: $record.decod... |
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 ... | #F.23 | F# |
//Floyd's algorithm: Nigel Galloway August 5th 2018
let Floyd (n:'a[]) (g:Map<('a*'a),int>)= //nodes graph(Map of adjacency list)
let ix n g=Seq.init (pown g n) (fun x->List.unfold(fun (a,b)->if a=0 then None else Some(b%g,(a-1,b/g)))(n,x))
let fN w (i,j,k)=match Map.tryFind(i,j) w,Map.tryFind(i,k) w,Map.tryFind(... |
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 ... | #Processing | Processing | float multiply(float x, float 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 ... | #Prolog | Prolog | multiply(A, B, P) :- P is A * B. |
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... | #J | J | fd=: 2&(-~/\) |
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... | #Java | Java | import java.util.Arrays;
public class FD {
public static void main(String args[]) {
double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
System.out.println(Arrays.toString(dif(a, 1)));
System.out.println(Arrays.toString(dif(a, 2)));
System.out.println(Arrays.toString(dif(a, 9)));
... |
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
| #X86_Assembly | X86 Assembly | section .data
msg db 'Hello world!', 0AH
len equ $-msg
section .text
global _start
_start: mov edx, len
mov ecx, msg
mov ebx, 1
mov eax, 4
int 80h
mov ebx, 0
mov eax, 1
int 80h |
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.
| #Oberon-2 | Oberon-2 | Out.Real(7.125, 9, 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.
| #Objective-C | Objective-C | NSLog(@"%09.3f", 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 ... | #Kotlin | Kotlin | // version 1.1.51
val Boolean.I get() = if (this) 1 else 0
val Int.B get() = this != 0
class Nybble(val n3: Boolean, val n2: Boolean, val n1: Boolean, val n0: Boolean) {
fun toInt() = n0.I + n1.I * 2 + n2.I * 4 + n3.I * 8
override fun toString() = "${n3.I}${n2.I}${n1.I}${n0.I}"
}
fun Int.toNybble(): N... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <pthread.h>
#include <SDL.h>
// defaults
#define PROB_TREE 0.55
#define PROB_F 0.00001
#define PROB_P 0.001
#define TIMERFREQ 100
#ifndef WIDTH
# define WIDTH 640
#endif
#ifndef HEIGHT
# define HEIGHT ... |
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
| #Arturo | Arturo | print flatten [[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 ... | #Clojure | Clojure | (defn cols [board]
(mapv vec (apply map list board)))
(defn flipv [v]
(mapv #(if (> % 0) 0 1) v))
(defn flip-row [board n]
(assoc board n (flipv (get board n))))
(defn flip-col [board n]
(cols (flip-row (cols board) n)))
(defn play-rand [board n]
(if (= n 0)
board
(let [f (if (= (rand-int 2) 0... |
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 ... | #11l | 11l | F p(=l, n, pwr = 2)
l = Int(abs(l))
V digitcount = floor(log(l, 10))
V log10pwr = log(pwr, 10)
V (raised, found) = (-1, 0)
L found < n
raised++
V firstdigits = floor(10 ^ (fract(log10pwr * raised) + digitcount))
I firstdigits == l
found++
R raised
L(l, n) [(12, 1), (12, 2)... |
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... | #Ada | Ada | with Ada.Text_IO;
procedure Firstclass is
generic
n1, n2 : Float;
function Multiplier (m : Float) return Float;
function Multiplier (m : Float) return Float is
begin
return n1 * n2 * m;
end Multiplier;
num, inv : array (1 .. 3) of Float;
begin
num := (2.0, 4.0, 6.0);
inv := (1.0/2.... |
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... | #ALGOL_68 | ALGOL 68 | REAL
x := 2,
xi := 0.5,
y := 4,
yi := 0.25,
z := x + y,
zi := 1 / ( x + y );
MODE F = PROC(REAL)REAL;
PROC multiplier = (REAL n1, n2)F: ((REAL m)REAL: n1 * n2 * m);
# Numbers as members of collections #
[]REAL num list = (x, y, z),
inv num list = (xi, yi, zi);
# Apply numbers from list #
... |
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... | #Erlang | Erlang | : checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
2DUP @ 0 SWAP WITHIN IF
SWAP 1+ CELLS +
ELSE
1 THROW
THEN ;
8 checked-array myarray
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ; |
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... | #Forth | Forth | : checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
2DUP @ 0 SWAP WITHIN IF
SWAP 1+ CELLS +
ELSE
1 THROW
THEN ;
8 checked-array myarray
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ; |
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... | #R | R |
# provided by neonira
integerToText <- function(value_n_1) {
english_words_for_numbers <- list(
simples = c(
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
... |
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... | #Racket | Racket |
#lang racket
(require rackunit)
(define smalls
(map symbol->string
'(zero one two three four five six seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen seventeen eighteen nineteen)))
(define tens
(map symbol->string
'(zero ten 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... | #Arturo | Arturo | floyd: function [rowcount][
result: new [[1]]
while [rowcount > size result][
n: inc last last result
row: new []
loop n..n+size last result 'k -> 'row ++ @[k]
'result ++ @[row]
]
return result
]
loop [5 14] 'j [
f: floyd j
loop f 'row -> print map row 'r [pad t... |
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #REBOL | REBOL |
inp: open %infile.dat
out: open/new %outfile.dat
while [ not empty? line: copy/part inp 80 ][ write out reverse line ]
close inp
close out
|
http://rosettacode.org/wiki/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #REXX | REXX | /*REXX pgm reads fixed─length 80 byte records; reverses each record, displays to term. */
iFID= 'FIXEDLEN.TXT' /*the file's filename (used for input).*/
call charin iFID, 1, 0 /*open the file, point rec pointer to 1*/
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.