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/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 ... | #Oz | Oz | fun {Multiply X Y}
X * 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 ... | #PARI.2FGP | PARI/GP | multiply(a,b)=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... | #EchoLisp | EchoLisp |
(define (Δ-1 list)
(for/list ([x (cdr list)] [y list]) (- x y)))
(define (Δ-n n) (iterate Δ-1 n))
((Δ-n 9) '(90 47 58 29 22 32 55 5 55 73))
→ (-2921)
|
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
| #Vlang | Vlang | fn main() {
println('Hello World!')
} |
http://rosettacode.org/wiki/Formal_power_series | Formal power series | A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ... | #Tcl | Tcl | package require TclOO
oo::class create PowerSeries {
variable name
constructor {{body {}} args} {
# Use the body to adapt the methods of the _object_
oo::objdefine [self] $body
# Use the rest to configure variables in the object
foreach {var val} $args {
set [my varname $var] $val
}
... |
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.
| #IS-BASIC | IS-BASIC | 100 LET F=7.125
110 PRINT USING "-%%%%%.###":F |
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.
| #J | J | 'r<0>9.3' (8!:2) 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 ... | #FreeBASIC | FreeBASIC | sub half_add( byval a as ubyte, byval b as ubyte,_
byref s as ubyte, byref c as ubyte)
s = a xor b
c = a and b
end sub
sub full_add( byval a as ubyte, byval b as ubyte, byval c as ubyte,_
byref s as ubyte, byref g as ubyte )
dim as ubyte x, y, z
half_add( a, c, x, y )
h... |
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... | #11l | 11l | V n = 10
Int result
L(i) 0 .< n
I (n % 2) == 0
L.continue
I (n % i) == 0
result = i
L.break
L.was_no_break
result = -1
print(‘No odd factors found’) |
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... | #Haskell | Haskell | module Main where
import Data.List (find)
import Data.Char (toUpper)
firstNums :: [String]
firstNums =
[ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
]
tens :: [S... |
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 ... | #360_Assembly | 360 Assembly | * Floyd-Warshall algorithm - 06/06/2018
FLOYDWAR CSECT
USING FLOYDWAR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
S... |
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 ... | #Pascal | Pascal | function multiply(a, b: real): real;
begin
multiply := a * b
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 ... | #Perl | Perl | sub multiply { return $_[0] * $_[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... | #Elixir | Elixir | defmodule Diff do
def forward(list,i\\1) do
forward(list,[],i)
end
def forward([_],diffs,1), do: IO.inspect diffs
def forward([_],diffs,i), do: forward(diffs,[],i-1)
def forward([val1,val2|vals],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
Enum.each(1..9, fn i ->
Diff.forward(... |
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... | #Erlang | Erlang | -module(forward_difference).
-export([difference/1, difference/2]).
-export([task/0]).
-define(TEST_DATA,[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]).
difference([X|Xs]) ->
{Result,_} = lists:mapfoldl(fun (N_2,N_1) -> {N_2 - N_1, N_2} end, X, Xs),
Result.
difference([],_) -> [];
difference(List,0) -> List;
di... |
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
| #VTL-2 | VTL-2 | 10 ?="Hello world!" |
http://rosettacode.org/wiki/Formal_power_series | Formal power series | A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ... | #Wren | Wren | import "/rat" for Rat
class Gene {
coef(n) {}
}
class Term {
construct new(gene) {
_gene = gene
_cache = []
}
gene { _gene }
[n] {
if (n < 0) return Rat.zero
if (n >= _cache.count) {
for (i in _cache.count..n) _cache.add(gene.coef(i))
}
... |
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.
| #Java | Java | public class Printing{
public static void main(String[] args){
double value = 7.125;
System.out.printf("%09.3f",value); // System.out.format works the same way
System.out.println(String.format("%09.3f",value));
}
} |
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.
| #JavaScript | JavaScript | var n = 123;
var str = ("00000" + n).slice(-5);
alert(str); |
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 ... | #Go | Go | package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v,... |
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... | #360_Assembly | 360 Assembly |
B TESTPX goto label TESTPX
BR 14 goto to the address found in register 14
|
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... | #6502_Assembly | 6502 Assembly | JMP $8000 ;immediately JuMP to $8000 and begin executing
;instructions there. |
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... | #J | J |
names =. 'one';'two';'three';'four';'five';'six';'seven';'eight';'nine';'ten';'eleven';'twelve';'thirteen';'fourteen';'fifteen';'sixteen';'seventeen';'eighteen';'nineteen'
tens =. '';'twenty';'thirty';'forty';'fifty';'sixty';'seventy';'eighty';'ninety'
NB. selects the xth element from list y
lookup =: >@{:@{.
N... |
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... | #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
subtype Block is String (1 .. 80);
Infile_Name : String := "infile.dat";
outfile_Name : String := "outfile.dat";
Infile : File_Type;
outfile : File_Type;
Line : Block := (Others => ' ');
begin
Open (File => Infile, Mode => In_Fi... |
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 ... | #Ada | Ada | --
-- Floyd-Warshall algorithm.
--
-- See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
--
with Ada.Containers.Vectors;
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
with Ada.Numerics.Generic_Elementary_Functions;
procedure floyd_warshall_task
... |
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 ... | #Phix | Phix | with javascript_semantics
function multiply(atom a, atom b)
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... | #F.23 | F# | let rec ForwardDifference input n =
match n with
| _ when input = [] || n < 0 -> [] // If there's no more input, just return an empty list
| 0 -> input // If n is zero, we're done - return the input
| _ -> ForwardDifference // otherwise, recursively differe... |
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
| #Wart | Wart | prn "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
| #WDTE | WDTE | io.writeln io.stdout 'Hello world!'; |
http://rosettacode.org/wiki/Formal_power_series | Formal power series | A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ... | #zkl | zkl | class IPS{
var [protected] w; // the coefficients of the infinite series
fcn init(w_or_a,b,c,etc){ // IPS(1,2,3) --> (1,2,3,0,0,...)
switch [arglist]{
case(Walker) { w=w_or_a.tweak(Void,0) }
else { w=vm.arglist.walker().tweak(Void,0) }
}
}
fcn __opAdd(ipf){ //IPS(1,2,3)+IPS(4,5)-->IP... |
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.
| #jq | jq | def pp0(width):
tostring
| if width > length then (width - length) * "0" + . else . end;
# pp(left; right) formats a decimal number to occupy
# (left+right+1) positions if possible,
# where "left" is the number of characters to the left of
# the decimal point, and similarly for "right".
def pp(left; right):
def... |
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.
| #Julia | Julia | using Printf
test = [7.125, [rand()*10^rand(0:4) for i in 1:9]]
println("Formatting some numbers with the @sprintf macro (using \"%09.3f\"):")
for i in test
println(@sprintf " %09.3f" i)
end
using Formatting
println()
println("The same thing using the Formatting package:")
fe = FormatExpr(" {1:09.3f}")
fo... |
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 ... | #Groovy | Groovy | class Main {
static void main(args) {
def bit1, bit2, bit3, bit4, carry
def fourBitAdder = new FourBitAdder(
{ value -> bit1 = value },
{ value -> bit2 = value },
{ value -> bit3 = value },
{ value -> bit4 = value },
... |
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
| #8th | 8th |
\ take a list (array) and flatten it:
: (flatten) \ a -- a
(
\ is it a number?
dup >kind ns:n n:= if
\ yes. so add to the list
r> swap a:push >r
else
\ it is not, so flatten it
(flatten)
then
drop
) a:each drop ;
: flatten \ a -- a
[] >r (flatten) r> ;
[[1], 2, [[3,4], 5], [[[]]], [[[... |
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 ... | #11l | 11l | V ascii_lowercase = ‘abcdefghij’
V digits = ‘0123456789’ // to get round ‘bug in MSVC 2017’[https://developercommunity.visualstudio.com/t/bug-with-operator-in-c/565417]
V n = 3
V board = [[0] * n] * n
F setbits(&board, count = 1)
L 0 .< count
board[random:(:n)][random:(:n)] (+)= 1
F fliprow(i)
L(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... | #68000_Assembly | 68000 Assembly | <<Top>>
Put_Line("Hello, World");
goto Top; |
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... | #Ada | Ada | <<Top>>
Put_Line("Hello, World");
goto Top; |
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... | #Java | Java |
public class FourIsMagic {
public static void main(String[] args) {
for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {
... |
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... | #AWK | AWK |
# syntax: GAWK -f FIXED_LENGTH_RECORDS.AWK
BEGIN {
vlr_fn = "FIXED_LENGTH_RECORDS.TXT"
flr_fn = "FIXED_LENGTH_RECORDS.TMP"
print("bef:")
while (getline rec <vlr_fn > 0) { # read variable length records
printf("%-80.80s",rec) >flr_fn # write fixed length records without CR/LF
printf("%s\n",... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
void reverse(std::istream& in, std::ostream& out) {
constexpr size_t record_length = 80;
char record[record_length];
while (in.read(record, record_length)) {
std::reverse(std::begin(record), std::end(record));
o... |
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 ... | #ATS | ATS | (*
Floyd-Warshall algorithm.
See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
*)
#include "share/atspre_staload.hats"
#define NIL list_nil ()
#define :: list_cons
typedef Pos = [i : pos] int i
(*---------------------------------------------------------------... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #Phixmonti | Phixmonti | def multiply * enddef |
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 ... | #PHL | PHL | @Integer multiply(@Integer a, @Integer b) [
return 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... | #Factor | Factor | USING: kernel math math.vectors sequences ;
IN: rosetacode
: 1-order ( seq -- seq' )
[ rest-slice ] keep v- ;
: n-order ( seq n -- seq' )
dup 0 <=
[ drop ] [ [ 1-order ] times ] if ;
|
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... | #Forth | Forth | : forward-difference
dup 0
?do
swap rot over i 1+ - 0
?do dup i cells + dup cell+ @ over @ - swap ! loop
swap rot
loop -
;
create a
90 , 47 , 58 , 29 , 22 , 32 , 55 , 5 , 55 , 73 ,
: test a 10 9 forward-difference bounds ?do i ? loop ;
test |
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
| #WebAssembly | WebAssembly | (module $helloworld
;;Import fd_write from WASI, declaring that it takes 4 i32 inputs and returns 1 i32 value
(import "wasi_unstable" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32))
)
;;Declare initial memory size of 32 bytes
(memory 32)
;;Export memory so external... |
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.
| #Kotlin | Kotlin | // version 1.0.5-2
fun main(args: Array<String>) {
val num = 7.125
println("%09.3f".format(num))
} |
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.
| #Lambdatalk | Lambdatalk |
{def fmt
{def padd {lambda {:n :x} {if {< :n 1} then else :x{padd {- :n 1} :x}}}}
{def trunc {lambda {:n} {if {> :n 0} then {floor :n} else {ceil :n}}}}
{lambda {:a :b :n}
{let { {:a :a} {:b :b} {:n {abs :n}} {:sign {if {>= :n 0} then + else -}}
{:int {trunc :n}}
{:dec {ceil {* 1.0e:b {abs {-... |
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 ... | #Haskell | Haskell | import Control.Arrow
import Data.List (mapAccumR)
bor, band :: Int -> Int -> Int
bor = max
band = min
bnot :: Int -> Int
bnot = (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
| #ACL2 | ACL2 | (defun flatten (tr)
(cond ((null tr) nil)
((atom tr) (list tr))
(t (append (flatten (first tr))
(flatten (rest tr)))))) |
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 ... | #8080_Assembly | 8080 Assembly | ;;; Flip the Bits game, CP/M version.
;;; CP/M zero page locations
cmdln: equ 80h
;;; CP/M system calls
getch: equ 1h
putch: equ 2h
rawio: equ 6h
puts: equ 9h
org 100h
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Retrieve command line input. If it is not correct, end.
lxi d,... |
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... | #ALGOL_68 | ALGOL 68 | (
FOR j TO 1000 DO
FOR i TO j-1 DO
IF random > 0.999 THEN
printf(($"Exited when: i="g(0)", j="g(0)l$,i,j));
done
FI
# etc. #
OD
OD;
done: EMPTY
); |
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... | #ALGOL_W | ALGOL W | begin
integer i;
integer procedure getNumber ;
begin
integer n;
write( "n> " );
read( i );
if i< 0 then goto negativeNumber;
i
end getNumber ;
i := getNumber;
write( "positive or zero" );
go to endProgram;
negativeNumber:
writeon( "negative" );
e... |
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... | #JavaScript | JavaScript | Object.getOwnPropertyNames(this).includes('BigInt') |
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... | #Julia | Julia | # The num2text routines are from the "Number names" task, updated for Julia 1.0
const stext = ["one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"]
const teentext = ["eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen",
"ei... |
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... | #COBOL | COBOL | *> Rosetta Code, fixed length records
*> Tectonics:
*> cobc -xj lrecl80.cob
identification division.
program-id. lrecl80.
environment division.
configuration section.
repository.
function all intrinsic.
input-output section.
file-contro... |
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 ... | #C | C |
#include<limits.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int sourceVertex, destVertex;
int edgeWeight;
}edge;
typedef struct{
int vertices, edges;
edge* edgeMatrix;
}graph;
graph loadGraph(char* fileName){
FILE* fp = fopen(fileName,"r");
graph G;
int i;
fscanf(... |
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 ... | #PHP | PHP | function multiply( $a, $b )
{
return $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 ... | #Picat | Picat | multiply(A, B) = 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... | #Fortran | Fortran | MODULE DIFFERENCE
IMPLICIT NONE
CONTAINS
SUBROUTINE Fdiff(a, n)
INTEGER, INTENT(IN) :: a(:), n
INTEGER :: b(SIZE(a))
INTEGER :: i, j, arraysize
b = a
arraysize = SIZE(b)
DO i = arraysize-1, arraysize-n, -1
DO j = 1, i
b(j) = b(j+1) - b(j)
END DO
END DO
W... |
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
| #Wee_Basic | Wee Basic | print 1 "Hello world!"
end |
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.
| #Lasso | Lasso | 7.125 -> asstring(-precision = 3, -padding = 9, -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.
| #Liberty_BASIC | Liberty BASIC |
for i =1 to 10
n =rnd( 1) *10^( int( 10 *rnd(1)) -2)
print "Raw number ="; n; "Using custom function ="; FormattedPrint$( n, 16, 5)
next i
end
function FormattedPrint$( n, length, decPlaces)
format$ ="#."
for i =1 to decPlaces
format$ =format$ +"#"
next i
n$ =using( format$, n) ... |
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 ... | #Icon_and_Unicon | Icon and Unicon | #
# 4bitadder.icn, emulate a 4 bit adder. Using only and, or, not
#
record carry(c)
#
# excercise the adder, either "test" or 2 numbers
#
procedure main(argv)
c := carry(0)
# cli test
if map(\argv[1]) == "test" then {
# Unicon allows explicit radix literals
every i := (2r0000 | 2r1001 |... |
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... | #6502_Assembly | 6502 Assembly | ORG $4357
; SYS 17239 or CALL 17239
EMPTY2 = $00
TREE2 = $44
FIRE2 = $99
; common available zero page
GBASL = $26
GBASH = $27
SEED2 = $28
SEED0 = $29
SEED1 = $2A
H2 = $2B
V2 = $2C
PLOTC = $2D
COLOR = $2E
PAGE = $2F
TOPL = $30
TOPH = $31
MIDL = $32
MIDH = $33
BTML = $34
BTMH = $35
PLOTL = $36
PLOTH = $37
la... |
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
| #ActionScript | ActionScript | function flatten(input:Array):Array {
var output:Array = new Array();
for (var i:uint = 0; i < input.length; i++) {
//typeof returns "object" when applied to arrays. This line recursively evaluates nested arrays,
// although it may break if the array contains objects that are not array... |
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 ... | #8086_Assembly | 8086 Assembly | bits 16
cpu 8086
;;; MS-DOS PSP locations
arglen: equ 80h
argstart: equ 82h
;;; MS-DOS system calls
getch: equ 1h
putch: equ 2h
puts: equ 9h
time: equ 2Ch
section .text
org 100h
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Read board size from command line
cmp byte [arglen]... |
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... | #ARM_Assembly | ARM Assembly | SWI n ;software system call
B label ;Branch. Just "B" is a branch always, but any condition code can be added for a conditional branch.
;In fact, almost any instruction can be made conditional to avoid branching.
BL label ;Branch and Link. This is the equivalent of the CALL command on the x86 or Z80.... |
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... | #AutoHotkey | AutoHotkey | MsgBox, calling Label1
Gosub, Label1
MsgBox, Label1 subroutine finished
Goto Label2
MsgBox, calling Label2 ; this part is never reached
Return
Label1:
MsgBox, Label1
Return
Label2:
MsgBox, Label2 will not return to calling routine
Return |
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... | #Kotlin | Kotlin | // version 1.1.4-3
val names = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
10 to "ten",
11 to "eleven",
12 to "twelve",
13 to "thirteen",
14 to "fourteen",
15 to "fifteen",
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... | #Delphi | Delphi |
Const As Byte longRegistro = 80
Const archivoEntrada As String = "infile.dat"
Const archivoSalida As String = "outfile.dat"
Dim As String linea
'Abre el archivo origen para lectura
Open archivoEntrada For Input As #1
'Abre el archivo destino para escritura
Open archivoSalida For Output As #2
Print !"Datos de e... |
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... | #Free_Pascal | Free Pascal |
Const As Byte longRegistro = 80
Const archivoEntrada As String = "infile.dat"
Const archivoSalida As String = "outfile.dat"
Dim As String linea
'Abre el archivo origen para lectura
Open archivoEntrada For Input As #1
'Abre el archivo destino para escritura
Open archivoSalida For Output As #2
Print !"Datos de e... |
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 ... | #C.23 | C# | using System;
namespace FloydWarshallAlgorithm {
class Program {
static void FloydWarshall(int[,] weights, int numVerticies) {
double[,] dist = new double[numVerticies, numVerticies];
for (int i = 0; i < numVerticies; i++) {
for (int j = 0; j < numVerticies; 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 ... | #PicoLisp | PicoLisp | (de multiply (A B)
(* 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... | #FreeBASIC | FreeBASIC | function forward_difference( a() as uinteger ) as uinteger ptr
dim as uinteger ptr b = allocate( sizeof(uinteger) * (ubound(a)-1) )
for i as uinteger = 0 to ubound(a)-1
*(b+i) = a(i+1)-a(i)
next i
return b
end function
dim as uinteger a(0 to 15) = {2, 3, 5, 7, 11, 13, 17, 19,_
... |
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
| #Whenever | Whenever | 1 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.
| #Logo | Logo | to zpad :num :width :precision
output map [ifelse ? = "| | ["0] [?]] form :num :width :precision
end
print zpad 7.125 9 3 ; 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.
| #Lua | Lua | function digits(n) return math.floor(math.log(n) / math.log(10))+1 end
function fixedprint(num, digs) --digs = number of digits before decimal point
for i = 1, digs - digits(num) do
io.write"0"
end
print(num)
end
fixedprint(7.125, 5) --> 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 ... | #J | J | and=: *.
or=: +.
not=: -.
xor=: (and not) or (and not)~
hadd=: and ,"0 xor
add=: ((({.,0:)@[ or {:@[ hadd {.@]), }.@])/@hadd |
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... | #8086_Assembly | 8086 Assembly | ;;; Simulation settings (probabilities are P/65536)
probF: equ 7 ; P(spontaneous combustion) ~= 0.0001
probP: equ 655 ; P(spontaneous growth) ~= 0.01
HSIZE: equ 320 ; Field width (320x200 fills CGA screen)
VSIZE: equ 200 ; Field height
FSIZE: equ HSIZE*VSIZE ; Field size
FPARA: equ FSIZE/16+1 ; Field size in para... |
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
| #Ada | Ada | generic
type Element_Type is private;
with function To_String (E : Element_Type) return String is <>;
package Nestable_Lists is
type Node_Kind is (Data_Node, List_Node);
type Node (Kind : Node_Kind);
type List is access Node;
type Node (Kind : Node_Kind) is record
Next : List;
case... |
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 ... | #Action.21 | Action! | BYTE boardX=[13],boardY=[10],goalX=[22]
PROC UpdateBoard(BYTE ARRAY board BYTE side,x0,y0)
BYTE x,y
FOR y=0 TO side-1
DO
Position(x0,y0+2+y)
Put(y+'1)
FOR x=0 TO side-1
DO
IF y=0 THEN
Position(x0+2+x,y0)
Put(x+'A)
FI
Position(x0+2+x,y0+2+y)
PrintB(board(... |
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... | #AWK | AWK | $ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
2
4
6
8 |
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... | #BASIC256 | BASIC256 |
gosub subrutina
bucle:
print "Bucle infinito"
goto bucle
subrutina:
print "En subrutina"
pause 10
return
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... | #Lua | Lua | -- Four is magic, in Lua, 6/16/2020 db
local oneslist = { [0]="", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
local teenlist = { [0]="ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }
local tenslist = { [0]="", "", "twenty", "thirt... |
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... | #11l | 11l | F floyd(rowcount)
V rows = [[1]]
L rows.len < rowcount
V n = rows.last.last + 1
rows.append(Array(n .. n + rows.last.len))
R rows
F pfloyd(rows)
V colspace = rows.last.map(n -> String(n).len)
L(row) rows
print(zip(colspace, row).map2((space, n) -> String(n).rjust(space)).join(‘ ’))
... |
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... | #FreeBASIC | FreeBASIC |
Const As Byte longRegistro = 80
Const archivoEntrada As String = "infile.dat"
Const archivoSalida As String = "outfile.dat"
Dim As String linea
'Abre el archivo origen para lectura
Open archivoEntrada For Input As #1
'Abre el archivo destino para escritura
Open archivoSalida For Output As #2
Print !"Datos de e... |
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... | #Go | Go | package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func reverseBytes(bytes []byte) {
for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
bytes[i], bytes[j] = bytes[j], bytes[i]
}
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
in, ... |
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 ... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <sstream>
void print(std::vector<std::vector<double>> dist, std::vector<std::vector<int>> next) {
std::cout << "(pair, dist, path)" << std::endl;
const auto size = std::size(next);
for (auto i = 0; i < size; ++i) {
for (auto j = 0; j < size; ++j) {
if (i ... |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #Pike | Pike | int multiply(int a, int b){
return 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 ... | #PL.2FI | PL/I | PRODUCT: procedure (a, b) returns (float);
declare (a, b) float;
return (a*b);
end PRODUCT; |
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... | #Go | Go | package main
import "fmt"
func main() {
a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
fmt.Println(a)
fmt.Println(fd(a, 9))
}
func fd(a []int, ord int) []int {
for i := 0; i < ord; i++ {
for j := 0; j < len(a)-i-1; j++ {
a[j] = a[j+1] - a[j]
}
}
return a[:len... |
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
| #Whiley | Whiley | import whiley.lang.System
method main(System.Console console):
console.out.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
| #Whitespace | Whitespace | 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.
| #M2000_Interpreter | M2000 Interpreter |
Print str$(7.125,"00000.000")
|
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.
| #Maple | Maple | printf("%f", Pi);
3.141593
printf("%.0f", Pi);
3
printf("%.2f", Pi);
3.14
printf("%08.2f", Pi);
00003.14
printf("%8.2f", Pi);
3.14
printf("%-8.2f|", Pi);
3.14 |
printf("%+08.2f", Pi);
+0003.14
printf("%+0*.*f",8, 2, Pi);
+0003.14 |
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 ... | #Java | Java | public class GateLogic
{
// Basic gate interfaces
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
// Create NOT
public static One... |
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... | #Ada | Ada | with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Forest_Fire is
type Cell is (Empty, Tree, Fire);
type Board is array (Positive range <>, Positive range <>) of Cell;
procedure Step (S : in out Board; P, F : Float; Dice : Generator) is... |
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
| #Aikido | Aikido |
function flatten (list, result) {
foreach item list {
if (typeof(item) == "vector") {
flatten (item, result)
} else {
result.append (item)
}
}
}
var l = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
var newl = []
flatten (l, newl)
// print out the nicely f... |
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 ... | #Ada | Ada | with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Discrete_Random;
procedure Flip_Bits is
subtype Letter is Character range 'a' .. 'z';
Last_Col: constant letter := Ada.Command_Line.Argument(1)(1);
Last_Row: constant Positive := Positive'Value(Ada.Command_Line.Argument(2));
package Boolean_Rand is ne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.