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 created and values returned).
Related task
Function prototype
|
#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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#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
}
# Guess the name if not already set
if {![info exists [my varname name]]} {
set name [namespace tail [self]]
}
}
method name {} {
return $name
}
method term i {
return 0
}
method limit {} {
return inf
}
# A pretty-printer, that prints the first $terms non-zero terms
method print {terms} {
set result "${name}(x) == "
set limit [my limit]
if {$limit == 0} {
# Special case
return $result[my term 0]
}
set tCount 0
for {set i 0} {$tCount<$terms && $i<=$limit} {incr i} {
set t [my term $i]
if {$t == 0} continue
incr tCount
set t [format %.4g $t]
if {$t eq "1" && $i != 0} {set t ""}
if {$i == 0} {
append result "$t + "
} elseif {$i == 1} {
append result "${t}x + "
} else {
set p [string map {
0 \u2070 1 \u00b9 2 \u00b2 3 \u00b3 4 \u2074
5 \u2075 6 \u2076 7 \u2077 8 \u2078 9 \u2079
} $i]
append result "${t}x$p + "
}
}
return [string trimright $result "+ "]
}
# Evaluate (a prefix of) the series at a particular x
# The terms parameter gives the number; 5 is enough for show
method evaluate {x {terms 5}} {
set result 0
set limit [my limit]
set tCount 0
for {set i 0} {$tCount<$terms && $i<=$limit} {incr i} {
set t [my term $i]
if {$t == 0} continue
incr tCount
set result [expr {$result + $t * ($x ** $i)}]
}
return $result
}
# Operations to build new sequences from old ones
method add {s} {
PowerSeries new {
variable S1 S2
method limit {} {expr {max([$S1 limit],[$S2 limit])}}
method term i {
set t1 [expr {$i>[$S1 limit] ? 0 : [$S1 term $i]}]
set t2 [expr {$i>[$S2 limit] ? 0 : [$S2 term $i]}]
expr {$t1 + $t2}
}
} S1 [self] S2 $s name "$name+[$s name]"
}
method subtract {s} {
PowerSeries new {
variable S1 S2
method limit {} {expr {max([$S1 limit],[$S2 limit])}}
method term i {
set t1 [expr {$i>[$S1 limit] ? 0 : [$S1 term $i]}]
set t2 [expr {$i>[$S2 limit] ? 0 : [$S2 term $i]}]
expr {$t1 - $t2}
}
} S1 [self] S2 $s name "$name-[$s name]"
}
method integrate {{Name ""}} {
if {$Name eq ""} {set Name "Integrate\[[my name]\]"}
PowerSeries new {
variable S limit
method limit {} {
if {[info exists limit]} {return $limit}
try {
return [expr {[$S limit] + 1}]
} on error {} {
# If the limit spirals out of control, it's infinite!
return [set limit inf]
}
}
method term i {
if {$i == 0} {return 0}
set t [$S term [expr {$i-1}]]
expr {$t / double($i)}
}
} S [self] name $Name
}
method differentiate {{Name ""}} {
if {$Name eq ""} {set Name "Differentiate\[[my name]\]"}
PowerSeries new {
variable S
method limit {} {expr {[$S limit] ? [$S limit] - 1 : 0}}
method term i {expr {[incr i] * [$S term $i]}}
} S [self] name $Name
}
# Special constructor for making constants
self method constant n {
PowerSeries new {
variable n
method limit {} {return 0}
method term i {return $n}
} n $n name $n
}
}
# Define the two power series in terms of each other
PowerSeries create cos ;# temporary dummy object...
rename [cos integrate "sin"] sin
cos destroy ;# remove the dummy to make way for the real one...
rename [[PowerSeries constant 1] subtract [sin integrate]] cos
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 )
half_add( x, b, s, z )
g = y or z
end sub
sub fourbit_add( byval a3 as ubyte, byval a2 as ubyte, byval a1 as ubyte, byval a0 as ubyte,_
byval b3 as ubyte, byval b2 as ubyte, byval b1 as ubyte, byval b0 as ubyte,_
byref s3 as ubyte, byref s2 as ubyte, byref s1 as ubyte, byref s0 as ubyte,_
byref carry as ubyte )
dim as ubyte c2, c1, c0
full_add(a0, b0, 0, s0, c0)
full_add(a1, b1, c0, s1, c1)
full_add(a2, b2, c1, s2, c2)
full_add(a3, b3, c2, s3, carry )
end sub
dim as ubyte s3, s2, s1, s0, carry
print "1100 + 0011 = ";
fourbit_add( 1, 1, 0, 0, 0, 0, 1, 1, s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0
print "1111 + 0001 = ";
fourbit_add( 1, 1, 1, 1, 0, 0, 0, 1, s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0
print "1111 + 1111 = ";
fourbit_add( 1, 1, 1, 1, 1, 1, 1, 1, s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0
|
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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#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 :: [String]
tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
biggerNumbers :: [(Int, String)]
biggerNumbers =
[(100, "hundred"), (1000, "thousand"), (1000000, "million"), (1000000000, "billion"), (1000000000000, "trillion")]
cardinal :: Int -> String
cardinal n
| n' < 20 =
negText ++ firstNums !! n'
| n' < 100 =
negText ++ tens !! (n' `div` 10 - 2) ++ if n' `mod` 10 /= 0 then "-" ++ firstNums !! (n' `mod` 10) else ""
| otherwise =
let (num, name) =
maybe
(last biggerNumbers)
fst
(find (\((num_, _), (num_', _)) -> n' < num_') (zip biggerNumbers (tail biggerNumbers)))
smallerNum = cardinal (n' `div` num)
in negText ++ smallerNum ++ " " ++ name ++ if n' `mod` num /= 0 then " " ++ cardinal (n' `mod` num) else ""
where
n' = abs n
negText = if n < 0 then "negative " else ""
capitalized :: String -> String
capitalized (x : xs) = toUpper x : xs
capitalized [] = []
magic :: Int -> String
magic =
go True
where
go first num =
let cardiNum = cardinal num
in (if first then capitalized else id) cardiNum ++ " is "
++ if num == 4
then "magic."
else cardinal (length cardiNum) ++ ", " ++ go False (length cardiNum)
main :: IO ()
main = do
putStrLn $ magic 3
putStrLn $ magic 15
putStrLn $ magic 4
putStrLn $ magic 10
putStrLn $ magic 20
putStrLn $ magic (-13)
putStrLn $ magic 999999
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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
ST R15,8(R13) link forward
LR R13,R15 set addressability
MVC A+8,=F'-2' a(1,3)=-2
MVC A+VV*4,=F'4' a(2,1)= 4
MVC A+VV*4+8,=F'3' a(2,3)= 3
MVC A+VV*8+12,=F'2' a(3,4)= 2
MVC A+VV*12+4,=F'-1' a(4,2)=-1
LA R8,1 k=1
DO WHILE=(C,R8,LE,V) do k=1 to v
LA R10,A @a
LA R6,1 i=1
DO WHILE=(C,R6,LE,V) do i=1 to v
LA R7,1 j=1
DO WHILE=(C,R7,LE,V) do j=1 to v
LR R1,R6 i
BCTR R1,0
MH R1,=AL2(VV)
AR R1,R8 k
SLA R1,2
L R9,A-4(R1) a(i,k)
LR R1,R8 k
BCTR R1,0
MH R1,=AL2(VV)
AR R1,R7 j
SLA R1,2
L R3,A-4(R1) a(k,j)
AR R9,R3 w=a(i,k)+a(k,j)
L R2,0(R10) a(i,j)
IF CR,R2,GT,R9 THEN if a(i,j)>w then
ST R9,0(R10) a(i,j)=w
ENDIF , endif
LA R10,4(R10) next @a
LA R7,1(R7) j++
ENDDO , enddo j
LA R6,1(R6) i++
ENDDO , enddo i
LA R8,1(R8) k++
ENDDO , enddo k
LA R10,A @a
LA R6,1 f=1
DO WHILE=(C,R6,LE,V) do f=1 to v
LA R7,1 t=1
DO WHILE=(C,R7,LE,V) do t=1 to v
IF CR,R6,NE,R7 THEN if f^=t then do
LR R1,R6 f
XDECO R1,XDEC edit f
MVC PG+0(4),XDEC+8 output f
LR R1,R7 t
XDECO R1,XDEC edit t
MVC PG+8(4),XDEC+8 output t
L R2,0(R10) a(f,t)
XDECO R2,XDEC edit a(f,t)
MVC PG+12(4),XDEC+8 output a(f,t)
XPRNT PG,L'PG print
ENDIF , endif
LA R10,4(R10) next @a
LA R7,1(R7) t++
ENDDO , enddo t
LA R6,1(R6) f++
ENDDO , enddo f
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
VV EQU 4
V DC A(VV)
A DC (VV*VV)F'99999999' a(vv,vv)
PG DC CL80' . -> . .'
XDEC DS CL12
YREGS
END FLOYDWAR
|
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 created and values returned).
Related task
Function prototype
|
#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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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([90, 47, 58, 29, 22, 32, 55, 5, 55, 73],i)
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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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;
difference(List,Order) -> difference(difference(List),Order-1).
task() ->
io:format("Initial: ~p~n",[?TEST_DATA]),
[io:format("~3b: ~p~n",[N,difference(?TEST_DATA,N)]) || N <- lists:seq(0,length(?TEST_DATA))],
ok.
|
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 the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#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))
}
return _cache[n]
}
}
class FormalPS {
static DISP_TERM { 12 }
static X_VAR { "x" }
construct new() {
_term = null
}
construct new(term) {
_term = term
}
term { _term }
static fromPolynomial(polynomial) {
class PolyGene is Gene {
construct new (polynomial) { _polynomial = polynomial }
coef(n) { (n < 0 || n >= _polynomial.count) ? Rat.zero : _polynomial[n] }
}
return FormalPS.new(Term.new(PolyGene.new(polynomial)))
}
copyFrom(other) { _term = other.term }
inverseCoef(n) {
var res = List.filled(n+1, null)
res[0] = _term[0].inverse
if (n > 0) {
for (i in 1..n) {
res[i] = Rat.zero
for (j in 0...i) res[i] = res[i] + _term[i - j] * res[j]
res[i] = -res[0] * res[i]
}
}
return res[n]
}
+(other) {
class AddGene is Gene {
construct new(fps, other) {
_fps = fps
_other = other
}
coef(n) { _fps.term[n] + _other.term[n] }
}
return FormalPS.new(Term.new(AddGene.new(this, other)))
}
-(other) {
class SubGene is Gene {
construct new(fps, other) {
_fps = fps
_other = other
}
coef(n) { _fps.term[n] - _other.term[n] }
}
return FormalPS.new(Term.new(SubGene.new(this, other)))
}
*(other) {
class MulGene is Gene {
construct new(fps, other) {
_fps = fps
_other = other
}
coef(n) {
var res = Rat.zero
for (i in 0..n) res = res + _fps.term[i] * _other.term[n-i]
return res
}
}
return FormalPS.new(Term.new(MulGene.new(this, other)))
}
/(other) {
class DivGene is Gene {
construct new(fps, other) {
_fps = fps
_other = other
}
coef(n) {
var res = Rat.zero
for (i in 0..n) res = res + _fps.term[i] * _other.inverseCoef(n-i)
return res
}
}
return FormalPS.new(Term.new(DivGene.new(this, other)))
}
diff() {
class DiffGene is Gene {
construct new(fps) { _fps = fps }
coef(n) { _fps.term[n+1] * Rat.new(n+1) }
}
return FormalPS.new(Term.new(DiffGene.new(this)))
}
intg() {
class IntgGene is Gene {
construct new(fps) { _fps= fps }
coef(n) { (n == 0) ? Rat.zero : _fps.term[n-1] * Rat.new(1, n) }
}
return FormalPS.new(Term.new(IntgGene.new(this)))
}
toString_(dpTerm) {
var sb = ""
var c = _term[0]
Rat.showAsInt = true
var supers = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹", "¹⁰", "¹¹"]
if (c != Rat.zero) sb = sb + c.toString
for (i in 1...dpTerm) {
c = term[i]
if (c != Rat.zero) {
if (c > Rat.zero && sb.count > 0) sb = sb + " + "
var xvar = FormalPS.X_VAR
sb = sb +
((c == Rat.one) ? xvar :
(c == Rat.minusOne) ? " - %(xvar)" :
(c.num < 0) ? " - %(-c)%(xvar)" : "%(c)%(xvar)")
if (i > 1) sb = sb + "%(supers[i])"
}
}
if (sb.count == 0) sb = "0"
sb = sb + " + ..."
return sb
}
toString { toString_(FormalPS.DISP_TERM) }
}
var cos = FormalPS.new()
var sin = cos.intg()
var tan = sin/cos
cos.copyFrom(FormalPS.fromPolynomial([Rat.one]) - sin.intg())
System.print("sin(x) = %(sin)")
System.print("cos(x) = %(cos)")
System.print("tan(x) = %(tan)")
System.print("sin'(x) = %(sin.diff())")
var exp = FormalPS.new()
exp.copyFrom(FormalPS.fromPolynomial([Rat.one]) + exp.intg())
System.print("exp(x) = %(exp)")
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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, s3, s2, s1, s0 byte) {
s0, c0 := fa(a0, b0, 0)
s1, c1 := fa(a1, b1, c0)
s2, c2 := fa(a2, b2, c1)
s3, v = fa(a3, b3, c2)
return
}
func main() {
// add 10+9 result should be 1 0 0 1 1
fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}
|
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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#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 =: >@{:@{.
NB. string formatting
addspace =: ((' '"_, ]) ` ]) @. (<&0 @ {: @ $)
NB. numbers in range 1 to 19
s1 =: lookup&names
NB. numbers in range 20 to 99
s2d=: (lookup&tens @ <. @ %&10) , addspace @ (s1 @ (10&|))
NB. numbers in range 100 to 999
s3d =: s1 @ (<.@%&100), ' hundred', addspace @ s2d @ (100&|)
NB. numbers in range 1 to 999
s123d =: s1 ` s2d ` s3d @. (>& 19 + >&99)
NB. numbers in range 1000 to 999999
s456d =: (s123d @<.@%&1000), ' thousand', addspace @ s123d @ (1000&|)
NB. stringify numbers in range 1 to 999999
stringify =: s123d ` s456d @. (>&999)
NB. takes an int and returns an int of the length of the string of the input
lengthify =: {: @ $ @ stringify
NB. determines the string that should go after ' is '
what =: ((stringify @ lengthify), (', '"_)) ` ('magic'"_) @. (=&4)
runonce =: stringify , ' is ', what
run =: runonce, ((run @ lengthify) ` (''"_) @. (=&4))
doall =: run"0
inputs =: 4 8 16 25 89 365 2586 25865 369854
doall inputs
|
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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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_File, Name => Infile_Name);
Create (File => outfile, Mode => Out_File, Name => outfile_Name);
Put_Line("Input data:");
New_Line;
while not End_Of_File (Infile) loop
Get (File => Infile, Item => Line);
Put(Line);
New_Line;
for I in reverse Line'Range loop
Put (File => outfile, Item => Line (I));
end loop;
end loop;
Close (Infile);
Close (outfile);
Open(File => infile,
Mode => In_File,
Name => outfile_name);
New_Line;
Put_Line("Output data:");
New_Line;
while not End_Of_File(Infile) loop
Get(File => Infile,
Item => Line);
Put(Line);
New_Line;
end loop;
end Main;
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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
is
Floyd_Warshall_Exception : exception;
-- The floating point type we shall use is one that has infinities.
subtype FloatPt is IEEE_Float_32;
package FloatPt_Elementary_Functions is new Ada.Numerics
.Generic_Elementary_Functions
(FloatPt);
use FloatPt_Elementary_Functions;
-- The following should overflow and give us an IEEE infinity. But I
-- have kept the code so you could use some non-IEEE floating point
-- format and set ENORMOUS_FloatPt to some value that is finite but
-- much larger than actual graph traversal distances.
ENORMOUS_FloatPt : constant FloatPt :=
(FloatPt (1.0) / FloatPt (1.0e-37))**1.0e37;
--
-- Input is a Vector of records representing the edges of a graph.
--
-- Vertices are identified by integers from 1 .. n.
--
type edge is record
u : Positive;
weight : FloatPt;
v : Positive;
end record;
package Edge_Vectors is new Ada.Containers.Vectors
(Index_Type => Positive, Element_Type => edge);
use Edge_Vectors;
subtype edge_vector is Edge_Vectors.Vector;
--
-- Floyd-Warshall.
--
type distance_array is
array (Positive range <>, Positive range <>) of FloatPt;
type next_vertex_array is
array (Positive range <>, Positive range <>) of Natural;
Nil_Vertex : constant Natural := 0;
function find_max_vertex -- Find the maximum vertex number.
(edges : in edge_vector)
return Positive
is
max_vertex : Positive;
begin
if Is_Empty (edges) then
raise Floyd_Warshall_Exception with "no edges";
end if;
max_vertex := 1;
for i in edges.First_Index .. edges.Last_Index loop
max_vertex := Positive'Max (max_vertex, edges.Element (i).u);
max_vertex := Positive'Max (max_vertex, edges.Element (i).v);
end loop;
return max_vertex;
end find_max_vertex;
procedure floyd_warshall -- Perform Floyd-Warshall.
(edges : in edge_vector;
max_vertex : in Positive;
distance : out distance_array;
next_vertex : out next_vertex_array)
is
u, v : Positive;
dist_ikj : FloatPt;
begin
-- Initialize.
for i in 1 .. max_vertex loop
for j in 1 .. max_vertex loop
distance (i, j) := ENORMOUS_FloatPt;
next_vertex (i, j) := Nil_Vertex;
end loop;
end loop;
for i in edges.First_Index .. edges.Last_Index loop
u := edges.Element (i).u;
v := edges.Element (i).v;
distance (u, v) := edges.Element (i).weight;
next_vertex (u, v) := v;
end loop;
for i in 1 .. max_vertex loop
distance (i, i) :=
FloatPt (0.0); -- Distance from a vertex to itself.
next_vertex (i, i) := i;
end loop;
-- Perform the algorithm.
for k in 1 .. max_vertex loop
for i in 1 .. max_vertex loop
for j in 1 .. max_vertex loop
dist_ikj := distance (i, k) + distance (k, j);
if dist_ikj < distance (i, j) then
distance (i, j) := dist_ikj;
next_vertex (i, j) := next_vertex (i, k);
end if;
end loop;
end loop;
end loop;
end floyd_warshall;
--
-- Path reconstruction.
--
procedure put_path
(next_vertex : in next_vertex_array;
u, v : in Positive)
is
i : Positive;
begin
if next_vertex (u, v) /= Nil_Vertex then
i := u;
Put (Positive'Image (i));
while i /= v loop
Put (" ->");
i := next_vertex (i, v);
Put (Positive'Image (i));
end loop;
end if;
end put_path;
example_graph : edge_vector;
max_vertex : Positive;
begin
Append (example_graph, (u => 1, weight => FloatPt (-2.0), v => 3));
Append (example_graph, (u => 3, weight => FloatPt (+2.0), v => 4));
Append (example_graph, (u => 4, weight => FloatPt (-1.0), v => 2));
Append (example_graph, (u => 2, weight => FloatPt (+4.0), v => 1));
Append (example_graph, (u => 2, weight => FloatPt (+3.0), v => 3));
max_vertex := find_max_vertex (example_graph);
declare
distance : distance_array (1 .. max_vertex, 1 .. max_vertex);
next_vertex : next_vertex_array
(1 .. max_vertex, 1 .. max_vertex);
begin
floyd_warshall (example_graph, max_vertex, distance, next_vertex);
Put_Line (" pair distance path");
Put_Line ("---------------------------------------------");
for u in 1 .. max_vertex loop
for v in 1 .. max_vertex loop
if u /= v then
Put (Positive'Image (u));
Put (" ->");
Put (Positive'Image (v));
Put (" ");
Put (FloatPt'Image (distance (u, v)));
Put (" ");
put_path (next_vertex, u, v);
Put_Line ("");
end if;
end loop;
end loop;
end;
end 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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 difference..
(input.Tail // All but the first element
|> Seq.zip input // tupled with itself
|> Seq.map (fun (a, b) -> b-a) // Subtract the i'th element from the (i+1)'th
|> Seq.toList) (n-1) // Make into a list and do an n-1 difference on it
|
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 the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#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)-->IPS(5,6,3,0,...), returns modified self
switch[arglist]{
case(1){ addConst(ipf) } // IPS + int/float
else { w=w.zipWith('+,ipf.w) } // IPS + IPS
}
self
}
fcn __opSub(ipf){ w=w.zipWith('-,ipf.w); self } // IPS - IPSHaskell
fcn __opMul(ipf){ } // stub
fcn __opDiv(x){ w.next().toFloat()/x } // *IPS/x, for integtate()
fcn __opNegate { w=w.tweak(Op("--")); self }
// integtate: b0 = 0 by convention, bn = an-1/n
fcn integrate{ w=w.zipWith('/,[1..]).push(0.0); self }
fcn diff { w=w.zipWith('*,[1..]); self }
fcn facts{ (1).walker(*).tweak(fcn(n){ (1).reduce(n,'*,1) }) } // 1!,2!...
fcn walk(n){ w.walk(n) }
fcn value(x,N=15){ ns:=[1..]; w.reduce(N,'wrap(s,an){ s + an*x.pow(ns.next()) }) }
fcn cons(k){ w.push(k); self } //--> k, a0, a1, a2, ...
// addConst(k) --> k + a0, a1, a2, ..., same as k + IPS
fcn addConst(k){ (w.next() + k) : w.push(_); self }
}
|
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 lpad: if (left > length) then ((left - length) * "0") + . else . end;
tostring as $s
| $s
| index(".") as $ix
| ((if $ix then $s[0:$ix] else $s end) | lpad) + "." +
(if $ix then $s[$ix+1:] | .[0:right] else "" 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.
|
#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}")
for i in test
printfmtln(fe, i)
end
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 },
{ value -> carry = value }
)
// 5 + 6 = 11
// 0101 i.e. 5
fourBitAdder.setNum1Bit1 false
fourBitAdder.setNum1Bit2 true
fourBitAdder.setNum1Bit3 false
fourBitAdder.setNum1Bit4 true
// 0110 i.e 6
fourBitAdder.setNum2Bit1 false
fourBitAdder.setNum2Bit2 true
fourBitAdder.setNum2Bit3 true
fourBitAdder.setNum2Bit4 false
def boolToInt = { bool ->
bool ? 1 : 0
}
println ("0101 + 0110 = ${boolToInt(bit1)}${boolToInt(bit2)}${boolToInt(bit3)}${boolToInt(bit4)}")
}
}
class Not {
Closure output
Not(output) {
this.output = output
}
def setInput(input) {
output !input
}
}
class And {
boolean input1
boolean input2
Closure output
And(output) {
this.output = output
}
def setInput1(input) {
this.input1 = input
output(input1 && input2)
}
def setInput2(input) {
this.input2 = input
output(input1 && input2)
}
}
class Nand {
And andGate
Not notGate
Nand(output) {
notGate = new Not(output)
andGate = new And({ value ->
notGate.setInput value
})
}
def setInput1(input) {
andGate.setInput1 input
}
def setInput2(input) {
andGate.setInput2 input
}
}
class Or {
Not firstInputNegation
Not secondInputNegation
Nand nandGate
Or(output) {
nandGate = new Nand(output)
firstInputNegation = new Not({ value ->
nandGate.setInput1 value
})
secondInputNegation = new Not({ value ->
nandGate.setInput2 value
})
}
def setInput1(input) {
firstInputNegation.setInput input
}
def setInput2(input) {
secondInputNegation.setInput input
}
}
class Xor {
And andGate
Or orGate
Nand nandGate
Xor(output) {
andGate = new And(output)
orGate = new Or({ value ->
andGate.setInput1 value
})
nandGate = new Nand({ value ->
andGate.setInput2 value
})
}
def setInput1(input) {
orGate.setInput1 input
nandGate.setInput1 input
}
def setInput2(input) {
orGate.setInput2 input
nandGate.setInput2 input
}
}
class Adder {
Or orGate
Xor xorGate1
Xor xorGate2
And andGate1
And andGate2
Adder(sumOutput, carryOutput) {
xorGate1 = new Xor(sumOutput)
orGate = new Or(carryOutput)
andGate1 = new And({ value ->
orGate.setInput1 value
})
xorGate2 = new Xor({ value ->
andGate1.setInput1 value
xorGate1.setInput1 value
})
andGate2 = new And({ value ->
orGate.setInput2 value
})
}
def setBit1(input) {
xorGate2.setInput1 input
andGate2.setInput2 input
}
def setBit2(input) {
xorGate2.setInput2 input
andGate2.setInput1 input
}
def setCarry(input) {
andGate1.setInput2 input
xorGate1.setInput2 input
}
}
class FourBitAdder {
Adder adder1
Adder adder2
Adder adder3
Adder adder4
FourBitAdder(bit1, bit2, bit3, bit4, carry) {
adder1 = new Adder(bit1, carry)
adder2 = new Adder(bit2, { value ->
adder1.setCarry value
})
adder3 = new Adder(bit3, { value ->
adder2.setCarry value
})
adder4 = new Adder(bit4, { value ->
adder3.setCarry value
})
}
def setNum1Bit1(input) {
adder1.setBit1 input
}
def setNum1Bit2(input) {
adder2.setBit1 input
}
def setNum1Bit3(input) {
adder3.setBit1 input
}
def setNum1Bit4(input) {
adder4.setBit1 input
}
def setNum2Bit1(input) {
adder1.setBit2 input
}
def setNum2Bit2(input) {
adder2.setBit2 input
}
def setNum2Bit3(input) {
adder3.setBit2 input
}
def setNum2Bit4(input) {
adder4.setBit2 input
}
}
|
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], [[[]]], [[[6]]], 7, 8, []]
dup . cr
flatten
. cr
bye
|
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 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#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) 0 .< :n
:board[i - 1][j] (+)= 1
F flipcol(i)
L(&row) :board
row[i] (+)= 1
F shuffle(board, count = 1)
L 0 .< count
I random:(0 .< 2) != 0
fliprow(random:(:n) + 1)
E
flipcol(random:(:n))
F pr(board, comment = ‘’)
print(comment)
print(‘ ’(0 .< :n).map(i -> :ascii_lowercase[i]).join(‘ ’))
print(‘ ’enumerate(board, 1).map((j, line) -> ([‘#2’.format(j)] [+] line.map(i -> String(i))).join(‘ ’)).join("\n "))
F init(&board)
setbits(&board, count' random:(:n) + 1)
V target = copy(board)
L board == target
shuffle(board, count' 2 * :n)
V prompt = ‘ X, T, or 1-#. / #.-#. to flip: ’.format(:n, :ascii_lowercase[0], :ascii_lowercase[:n - 1])
R (target, prompt)
V (target, prompt) = init(&board)
pr(target, ‘Target configuration is:’)
print(‘’)
V turns = 0
L board != target
turns++
pr(board, turns‘:’)
V ans = input(prompt).trim(‘ ’)
I (ans.len == 1 & ans C ascii_lowercase & ascii_lowercase.index(ans) < n)
flipcol(ascii_lowercase.index(ans))
E I ans != ‘’ & all(ans.map(ch -> ch C :digits)) & Int(ans) C 1 .. n
fliprow(Int(ans))
E I ans == ‘T’
pr(target, ‘Target configuration is:’)
turns--
E I ans == ‘X’
L.break
E
print(" I don't understand '#.'... Try again. (X to exit or T to show target)\n".format(ans[0.<9]))
turns--
L.was_no_break
print("\nWell done!\nBye.")
|
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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#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}) {
String magic = fourIsMagic(n);
System.out.printf("%d = %s%n", n, toSentence(magic));
}
}
private static final String toSentence(String s) {
return s.substring(0,1).toUpperCase() + s.substring(1) + ".";
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String fourIsMagic(long n) {
if ( n == 4 ) {
return numToString(n) + " is magic";
}
String result = numToString(n);
return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length());
}
private static final String numToString(long n) {
if ( n < 0 ) {
return "negative " + numToString(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : "");
}
}
|
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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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",rec)
}
close(vlr_fn)
close(flr_fn)
print("aft:")
getline rec <flr_fn # read entire file
while (length(rec) > 0) {
printf("%s\n",revstr(substr(rec,1,80),80))
rec = substr(rec,81)
}
exit(0)
}
function revstr(str,start) {
if (start == 0) {
return("")
}
return( substr(str,start,1) revstr(str,start-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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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));
out.write(record, record_length);
}
out.flush();
}
int main(int argc, char** argv) {
std::ifstream in("infile.dat", std::ios_base::binary);
if (!in) {
std::cerr << "Cannot open input file\n";
return EXIT_FAILURE;
}
std::ofstream out("outfile.dat", std::ios_base::binary);
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
try {
in.exceptions(std::ios_base::badbit);
out.exceptions(std::ios_base::badbit);
reverse(in, out);
} catch (const std::exception& ex) {
std::cerr << "I/O error: " << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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
(*------------------------------------------------------------------*)
(* Square arrays with 1-based indexing. *)
extern praxi
lemma_square_array_indices {n : pos}
{i, j : pos | i <= n; j <= n}
() :<prf>
[0 <= (i - 1) + ((j - 1) * n);
(i - 1) + ((j - 1) * n) < n * n]
void
typedef square_array (t : t@ype+, n : int) =
'{
side_length = int n,
elements = arrayref (t, n * n)
}
fn {t : t@ype}
make_square_array {n : nat}
(n : int n,
fill : t) : square_array (t, n) =
let
prval () = mul_gte_gte_gte {n, n} ()
in
'{
side_length = n,
elements = arrayref_make_elt (i2sz (n * n), fill)
}
end
fn {t : t@ype}
square_array_get_at {n : pos}
{i, j : pos | i <= n; j <= n}
(arr : square_array (t, n),
i : int i,
j : int j) : t =
let
prval () = lemma_square_array_indices {n} {i, j} ()
in
arrayref_get_at (arr.elements,
(i - 1) + ((j - 1) * arr.side_length))
end
fn {t : t@ype}
square_array_set_at {n : pos}
{i, j : pos | i <= n; j <= n}
(arr : square_array (t, n),
i : int i,
j : int j,
x : t) : void =
let
prval () = lemma_square_array_indices {n} {i, j} ()
in
arrayref_set_at (arr.elements,
(i - 1) + ((j - 1) * arr.side_length),
x)
end
overload [] with square_array_get_at
overload [] with square_array_set_at
(*------------------------------------------------------------------*)
typedef floatpt = float
extern castfn i2floatpt : int -<> floatpt
macdef arbitrary_floatpt = i2floatpt (12345)
typedef distance_array (n : int) = square_array (floatpt, n)
typedef vertex = [i : nat] int i
#define NIL_VERTEX 0
typedef next_vertex_array (n : int) = square_array (vertex, n)
typedef edge =
'{ (* The ' means this is allocated by the garbage collector.*)
u = vertex,
weight = floatpt,
v = vertex
}
typedef edge_list (n : int) = list (edge, n)
typedef edge_list = [n : int] edge_list (n)
prfn (* edge_list have non-negative size. *)
lemma_edge_list_param {n : int} (edges : edge_list n)
:<prf> [0 <= n] void =
lemma_list_param edges
(*------------------------------------------------------------------*)
fn
find_max_vertex (edges : edge_list) : vertex =
let
fun
loop {n : nat} .<n>.
(p : edge_list n,
u : vertex) : vertex =
case+ p of
| NIL => u
| head :: tail =>
loop (tail, max (max (u, (head.u)), (head.v)))
prval () = lemma_edge_list_param edges
in
assertloc (isneqz edges);
loop (edges, 0)
end
fn
floyd_warshall {n : int}
(edges : edge_list,
n : int n,
distance : distance_array n,
next_vertex : next_vertex_array n) : void =
let
val () = assertloc (1 <= n)
in
(* This implementation does NOT initialize (to any meaningful
value) elements of "distance" that would be set "infinite" in
the Wikipedia pseudocode. Instead you should use the
"next_vertex" array to determine whether there exists a finite
path from one vertex to another.
Thus we avoid any dependence on IEEE floating point or on the
settings of the FPU. *)
(* Initialize. *)
let
var i : Pos
in
for (i := 1; i <= n; i := succ i)
let
var j : Pos
in
for (j := 1; j <= n; j := succ j)
next_vertex[i, j] := NIL_VERTEX
end
end;
let
var p : edge_list
in
for (p := edges; list_is_cons p; p := list_tail p)
let
val head = list_head p
val u = head.u
val () = assertloc (u <> NIL_VERTEX)
val () = assertloc (u <= n)
val v = head.v
val () = assertloc (v <> NIL_VERTEX)
val () = assertloc (v <= n)
in
distance[u, v] := head.weight;
next_vertex[u, v] := v
end
end;
let
var i : Pos
in
for (i := 1; i <= n; i := succ i)
begin
(* Distance from a vertex to itself is zero. *)
distance[i, i] := i2floatpt (0);
next_vertex[i, i] := i
end
end;
(* Perform the algorithm. *)
let
var k : Pos
in
for (k := 1; k <= n; k := succ k)
let
var i : Pos
in
for (i := 1; i <= n; i := succ i)
let
var j : Pos
in
for (j := 1; j <= n; j := succ j)
if next_vertex[i, k] <> NIL_VERTEX
&& next_vertex[k, j] <> NIL_VERTEX then
let
val dist_ikj = distance[i, k] + distance[k, j]
in
if next_vertex[i, j] = NIL_VERTEX
|| dist_ikj < distance[i, j] then
begin
distance[i, j] := dist_ikj;
next_vertex[i, j] := next_vertex[i, k]
end
end
end
end
end
end
fn
print_path {n : int}
(n : int n,
next_vertex : next_vertex_array n,
u : Pos,
v : Pos) : void =
if 0 < n then
let
val () = assertloc (u <= n)
val () = assertloc (v <= n)
in
if next_vertex[u, v] <> NIL_VERTEX then
let
var i : Int
in
i := u;
print! (i);
while (i <> v)
let
val () = assertloc (1 <= i)
val () = assertloc (i <= n)
in
print! (" -> ");
i := next_vertex[i, v];
print! (i)
end
end
end
implement
main0 () =
let
(* One might notice that (because consing prepends rather than
appends) the order of edges here is *opposite* to that of some
other languages' implementations. But the order of the edges is
immaterial. *)
val example_graph = NIL
val example_graph =
'{u = 1, weight = i2floatpt (~2), v = 3} :: example_graph
val example_graph =
'{u = 3, weight = i2floatpt (2), v = 4} :: example_graph
val example_graph =
'{u = 4, weight = i2floatpt (~1), v = 2} :: example_graph
val example_graph =
'{u = 2, weight = i2floatpt (4), v = 1} :: example_graph
val example_graph =
'{u = 2, weight = i2floatpt (3), v = 3} :: example_graph
val n = find_max_vertex (example_graph)
val distance = make_square_array<floatpt> (n, arbitrary_floatpt)
val next_vertex = make_square_array<vertex> (n, NIL_VERTEX)
in
floyd_warshall (example_graph, n, distance, next_vertex);
println! (" pair distance path");
println! ("------------------------------------------");
let
var u : Pos
in
for (u := 1; u <= n; u := succ u)
let
var v : Pos
in
for (v := 1; v <= n; v := succ v)
if u <> v then
begin
print! (" ", u, " -> ", v, " ");
if i2floatpt (0) <= distance[u, v] then
print! (" ");
print! (distance[u, v], " ");
print_path (n, next_vertex, u, v);
println! ()
end
end
end
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 created and values returned).
Related task
Function prototype
|
#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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 functions can see it
(export "memory" (memory 0))
;;Declare test data starting at address 8
(data (i32.const 8) "Hello world!\n")
;;The entry point for WASI is called _start
(func $main (export "_start")
;;Write the start address of the string to address 0
(i32.store (i32.const 0) (i32.const 8))
;;Write the length of the string to address 4
(i32.store (i32.const 4) (i32.const 13))
;;Call fd_write to print to console
(call $fd_write
(i32.const 1) ;;Value of 1 corresponds to stdout
(i32.const 0) ;;The location in memory of the string pointer
(i32.const 1) ;;Number of strings to output
(i32.const 24) ;;Address to write number of bytes written
)
drop ;;Ignore return code
)
)
|
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 {- :n {trunc :n}}}}} }
} {br}{padd {- :a {W.length {trunc :n}}} >}
{if {W.equal? :sign -} then else :sign}:int.:dec{padd {- :b {W.length :dec}} 0} }}}
-> fmt
{def numbers
7.125
10.7
0.980
-1000
559.8
-69.99
4970.430}
-> numbers
{S.map {fmt 10 3} {numbers}}
->
>>>>>>>>> +7.125
>>>>>>>> +10.699
>>>>>>>>> +0.980
>>>>>> -1000.000
>>>>>>> +559.799
>>>>>>>> -69.990
>>>>>> +4970.430
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#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,usage ; Usage string
mvi c,puts ; Print that string when we need to
lxi h,cmdln ; Pointer to command line
mov a,m ; Get length
ana a ; Zero?
jc 5 ; Then print and stop
inx h ; Advance to first non-space element
inx h
mov a,m ; Get first character
sui '3' ; Minimum number
jc 5 ; If input was less than that, print and stop
adi 3 ; Add 3 back, giving the board size
cpi 9 ; Is it higher than 8 now?
jnc 5 ; Then print usage and stop
sta boardsz ; Store the board size
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Because there's no standard way in CP/M to get at any
;;; entropy (not even a clock), ask the user to supply some
;;; by pressing the keys on the keyboard.
lxi d,presskeys
call outs
mvi b,8 ; we want to do this 8 times, for 24 keys total
randouter: mvi c,3 ; there are 3 bytes of state for the RNG
lxi h,xabcdat+1
randinner: push h ; keep the pointer and counters
push b
waitkey: mvi c,rawio
mvi e,0FFh
call 5
ana a
jz waitkey
pop b ; restore the pointer and counters
pop h
xra m ; XOR key with data
mov m,a
inx h
dcr c ; Have we had 3 bytes yet?
jnz randinner
dcr b ; Have we done it 8 times yet?
jnz randouter
lxi d,welcome
call outs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Generate a random board
lxi h,board
lxi b,4001h ; B=81, C=1
genrand: call xabcrand
ana c
mov m,a
inx h
dcr b
jnz genrand
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copy board into goal
lxi h,board
lxi d,goal
mvi b,64
copygoal: mov a,m
stax d
inx h
inx d
dcr b
jnz copygoal
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Do a bunch of random flips on the board (5-20)
call xabcrand
ani 0Fh ; 0..15 flips
adi 5 ; 5..20 flips
sta sysflips
mov b,a ; Do that many flips
randflip: call xabcrand
call flip ; Unused bits in the random number are ignored
dcr b
jnz randflip
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the current state
gamestate: lxi d,smoves
call outs
lda usrflips
call outanum
lxi d,sgoal
call outs
lda sysflips
call outanum
lxi d,newline
call outs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the current board and the goal
;;; Print the header first
lxi d,sboardhdr
call outs
lda boardsz
lxi d,2041h ; E=letter (A), D=space
add e ; Last letter
mov b,a ; B = last letter
mvi l,2 ; Print two headers
header: mvi e,'A'
mov a,d
call outaspace
headerpart: mov a,e
cmp b
jc headerltr
mov a,d ; Print spaces for invalid positions
headerltr: call outaspace
mov a,e
inr a
mov e,a
cpi 'A'+8
jc headerpart
mvi a,9
call outa
dcr l ; Print two headers (for two boards)
jnz header
lxi d,newline
call outs
;;; Then print each line of the board
mvi c,0 ; Start with line 0
printline: lxi h,board ; Get position on board
mvi d,2 ; Run twice - print board and goal
prbrdline: mvi a,'1' ; Print line number
add c
call outaspace
push d
mov a,c ; Line offset in board
rlc
rlc
rlc
mov e,a
mvi d,0
dad d ; Add line offset
pop d ; Restore board counter
mvi b,0 ; Start with column 0
printcol: lda boardsz ; Valid position?
dcr a
cmp b
jnc printbit
mvi a,' ' ; No - print space
jmp printpos
printbit: mov a,m ; Yes - print 0 or 1
adi '0'
printpos: call outaspace
inx h ; Next board pos
inr b
mov a,b ; Done yet?
cpi 8
jnz printcol ; If not, print next column
mvi a,9
call outa
lxi h,goal ; Print goal line next
dcr d
jnz prbrdline
mvi a,13 ; Print newline
call outa
mvi a,10
call outa
inr c ; Next line
lda boardsz ; Valid line?
dcr a
cmp c
jnc printline
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Prompt the user for a move
lxi d,prompt ; Print prompt
call outs
readinput: mvi c,getch ; Read character
call 5
ori 32 ; Make letters lowercase
cpi 'q' ; Quit?
rz
cpi '9'+1 ; 9 or lower? assume number
jc nummove
sui 'a' ; Otherwise, assume letter
jc invalid ; So <'a' is invalid input
call checkmove ; See if the move is valid
jc invalid ; If not, wrong input
ori 128 ; Set high bit for column flip
call flip ; Do the flip
jmp checkboard ; See if the game is won
nummove: sui '1' ; Board array is 0-based of course
jc invalid ; Not on board = invalid input
call checkmove ; See if the move is vali
jc invalid
call flip ; Do the move (high bit clear for row)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; See if the user has won
checkboard: lda boardsz
dcr a
mov b,a ; B = line
checkrow: lda boardsz
dcr a
mov c,a ; C = column
checkcol: mov a,b
rlc ; Line * 8
rlc
rlc
add c ; + column = offset
push b ; Store line/column
mvi h,0 ; Position offset
mov l,a
lxi d,board ; Get board
dad d
mov b,m ; B = board position
lxi d,64 ; Goal = board+64
dad d
mov a,m ; A = goal position
cmp b ; Are they the same?
pop b ; Restore line/column
jnz nowin ; If not, the user hasn't won
dcr c ; If so, try next column position
jp checkcol
dcr b ; If column done, try next row
jp checkrow
;;; If we get here, the user has won
lxi d,win
jmp outs
;;; The user hasn't won yet, get another move
nowin: lxi h,usrflips ; Increment the user flips
inr m
jmp gamestate ; Print new game state, get new move
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Invalid input: erase it, beep, and get another character
invalid: lxi d,nope
call outs
jmp readinput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Check if the move in A is valid. Set carry if not.
checkmove: mov b,a
lda boardsz
dcr a
cmp b
mov a,b
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Flip row or column A & 7 (zero-indexed) on the board.
;;; Bit 7 set = column, else row.
flip: rlc ; Test bit 7 (and A*2)
jc flipcol
;;; Flip row
push b ; Keep registers
push h
ani 0Eh ; Get row number
rlc ; Calculate offset, A*4
rlc ; A*8
mvi b,0 ; BC = A
mov c,a
lxi h,board ; Get board pointer
dad b ; Add row offset
lxi b,0801h ; Max. 8 bits, and C=1 (to flip)
fliprowbit: mov a,m ; Get position
xra c ; Flip position
mov m,a ; Store position
inx h ; Increment pointer
dcr b ; Done yet?
jnz fliprowbit
pop h ; Restore registers
pop b
ret
;;; Flip column
flipcol: push b ; Keep registers
push d
push h
rrc ; Rotate A back
ani 7 ; Get column number
mvi d,0 ; Column offset
mov e,a
lxi h,board ; Get board pointer
dad d ; Add column offset
mvi e,8 ; Advance by 8 each time through the loop
lxi b,0801h ; Max. 8 bits, and C=1 (to flip)
flipcolbit: mov a,m ; Get position
xra c ; Flip position
mov m,a ; Store position
dad d ; Next row
dcr b ; Done yet?
jnz flipcolbit
pop h ; Restore registers
pop d
pop b
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The "X ABC" 8-bit random number generator
xabcrand: push h
lxi h,xabcdat
inr m ; X++
mov a,m ; X,
inx h ;
xra m ; ^ C,
inx h ;
xra m ; ^ A,
mov m,a ; -> A
inx h
add m ; + B,
mov m,a ; -> B
rar ; >>1
dcx h
xra m ; ^ A,
dcx h
add m ; + C
mov m,a ; -> C
pop h
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the string in DE. This saves one byte per call.
outs: mvi c,puts
jmp 5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the number in A in decimal, preserving registers
outanum: push psw
push b
push d
push h
lxi d,outabuf+3
outadgt: mvi b,-1
outdivmod: inr b
sui 10
jnc outdivmod
adi 10+'0'
dcx d
stax d
mov a,b
ana a
jnz outadgt
call outs
jmp regrestore
outabuf: db '***$' ; Room for ASCII number
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the character in A followed by a space, preserving
;;; registers.
outaspace: call outa
push psw
mvi a,' '
call outa
pop psw
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the character in A, preserving all registers.
outa: push psw
push b
push d
push h
mov e,a
mvi c,putch
call 5
regrestore: pop h
pop d
pop b
pop psw
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Strings
usage: db 'Usage: FLIP [3..8], number is board size.$'
presskeys: db 'Please press some keys to generate a random state...$'
welcome: db 'done.',13,10,13,10
db '*** FLIP THE BITS *** ',13,10
db '--------------------- ',
newline: db 13,10,'$'
smoves: db 13,10,13,10,'Your flips: $'
sgoal: db 9,'Goal: $'
sboardhdr: db '--Board------------',9,'--Goal-------------',13,10,'$'
prompt: db 'Press line or column to flip, or Q to quit: $'
nope: db 8,32,8,7,'$' ; Beep and erase input
win: db 13,10,7,7,7,'You win!$'
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Data
boardsz: ds 1 ; This will hold the board size
sysflips: ds 1 ; How many flips the system did
usrflips: ds 1 ; How many flips the user did
xabcdat: ds 4 ; RNG state
board: equ $
goal: equ board + 64 ; Max. 8*8 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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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" );
endProgram:
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 first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#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 first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#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",
"eighteen", "nineteen"]
const tenstext = ["ten", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"]
const ordstext = ["million", "billion", "trillion",
"quadrillion", "quintillion", "sextillion",
"septillion", "octillion", "nonillion",
"decillion", "undecillion", "duodecillion",
"tredecillion", "quattuordecillion", "quindecillion",
"sexdecillion", "septendecillion", "octodecillion",
"novemdecillion", "vigintillion"]
function normalize_digits!(a)
while 0 < length(a) && a[end] == 0
pop!(a)
end
return length(a)
end
function digits2text!(d, use_short_scale=true)
ndig = normalize_digits!(d)
0 < ndig || return ""
if ndig < 7
s = ""
if 3 < ndig
t = digits2text!(d[1:3])
s = digits2text!(d[4:end])*" thousand"
0 < length(t) || return s
if occursin("and", t)
return s*" "*t
else
return s*" and "*t
end
end
if ndig == 3
s *= stext[pop!(d)]*" hundred"
ndig = normalize_digits!(d)
0 < ndig || return s
s *= " and "
end
1 < ndig || return s*stext[pop!(d)]
j, i = d
j != 0 || return s*tenstext[i]
i != 1 || return s*teentext[j]
return s*tenstext[i]*"-"*stext[j]
end
s = digits2text!(d[1:6])
d = d[7:end]
dgrp = use_short_scale ? 3 : 6
ord = 0
while(dgrp < length(d))
ord += 1
t = digits2text!(d[1:dgrp])
d = d[(dgrp+1):end]
0 < length(t) || continue
t = t*" "*ordstext[ord]
if length(s) == 0
s = t
else
s = t*" "*s
end
end
ord += 1
t = digits2text!(d)*" "*ordstext[ord]
0 < length(s) || return t
return t*" "*s
end
function num2text(n, use_short_scale=true)
-1 < n || return "minus "*num2text(-n, use_short_scale)
0 < n || return "zero"
toobig = use_short_scale ? big(10)^66 : big(10)^126
n < toobig || return "too big to say"
return digits2text!(digits(n, base=10), use_short_scale)
end
function magic(n)
str = uppercasefirst(num2text(n))
n = length(str)
while true
numtext = num2text(n)
str *= " is " * numtext
if numtext == "four"
break
end
str *= ", " * numtext
n = length(numtext)
end
println(str[1:7] == "Four is" ? "Four is magic." : "$str, four is magic.")
end
for n in [0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209]
magic(n)
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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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-control.
select infile
assign to infile-name
organization is sequential
file status is infile-status
.
select outfile
assign to outfile-name
organization is sequential
file status is outfile-status
.
data division.
file section.
fd infile.
01 input-text pic x(80).
fd outfile.
01 output-text pic x(80).
working-storage section.
01 infile-name.
05 value "infile.dat".
01 infile-status pic xx.
88 ok-input value '00'.
88 eof-input value '10'.
01 outfile-name.
05 value "outfile.dat".
01 outfile-status pic xx.
88 ok-output value '00'.
procedure division.
open input infile
if not ok-input then
display "error opening input " infile-name upon syserr
goback
end-if
open output outfile
if not ok-output
display "error opening output " outfile-name upon syserr
goback
end-if
*> read lrecl 80 and write the reverse as lrecl 80
read infile
perform until not ok-input
move function reverse(input-text) to output-text
write output-text
if not ok-output then
display "error writing: " output-text upon syserr
end-if
read infile
end-perform
close infile outfile
*> from fixed length to normal text, outfile is now the input file
open input outfile
if not ok-output then
display "error opening input " outfile-name upon syserr
goback
end-if
read outfile
perform until not ok-output
display function trim(output-text trailing)
read outfile
end-perform
close outfile
goback.
end program lrecl80.
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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(fp,"%d%d",&G.vertices,&G.edges);
G.edgeMatrix = (edge*)malloc(G.edges*sizeof(edge));
for(i=0;i<G.edges;i++)
fscanf(fp,"%d%d%d",&G.edgeMatrix[i].sourceVertex,&G.edgeMatrix[i].destVertex,&G.edgeMatrix[i].edgeWeight);
fclose(fp);
return G;
}
void floydWarshall(graph g){
int processWeights[g.vertices][g.vertices], processedVertices[g.vertices][g.vertices];
int i,j,k;
for(i=0;i<g.vertices;i++)
for(j=0;j<g.vertices;j++){
processWeights[i][j] = SHRT_MAX;
processedVertices[i][j] = (i!=j)?j+1:0;
}
for(i=0;i<g.edges;i++)
processWeights[g.edgeMatrix[i].sourceVertex-1][g.edgeMatrix[i].destVertex-1] = g.edgeMatrix[i].edgeWeight;
for(i=0;i<g.vertices;i++)
for(j=0;j<g.vertices;j++)
for(k=0;k<g.vertices;k++){
if(processWeights[j][i] + processWeights[i][k] < processWeights[j][k]){
processWeights[j][k] = processWeights[j][i] + processWeights[i][k];
processedVertices[j][k] = processedVertices[j][i];
}
}
printf("pair dist path");
for(i=0;i<g.vertices;i++)
for(j=0;j<g.vertices;j++){
if(i!=j){
printf("\n%d -> %d %3d %5d",i+1,j+1,processWeights[i][j],i+1);
k = i+1;
do{
k = processedVertices[k-1][j];
printf("->%d",k);
}while(k!=j+1);
}
}
}
int main(int argC,char* argV[]){
if(argC!=2)
printf("Usage : %s <file containing graph data>");
else
floydWarshall(loadGraph(argV[1]));
return 0;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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
WRITE (*,*) b(1:arraysize-n)
END SUBROUTINE Fdiff
END MODULE DIFFERENCE
|
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) ' remove leading spaces if less than 3 figs left of decimal
' add leading zeros
for i =1 to len( n$)
c$ =mid$( n$, i, 1)
if c$ =" " or c$ ="%" then nn$ =nn$ +"0" else nn$ =nn$ +c$
next i
FormattedPrint$ =right$( "000000000000" +nn$, length) ' chop to required length
end function
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 | 2r1111) do {
write(i, "+0,3,9,15")
every j := (0 | 3 | 9 | 15) do {
ans := fourbitadder(t1 := fourbits(i), t2 := fourbits(j), c)
write(t1, " + ", t2, " = ", c.c, ":", ans)
}
}
return
}
# command line, two values, if given, first try four bit binaries
cli := fourbitadder(t1 := (*\argv[1] = 4 & fourbits("2r" || argv[1])),
t2 := (*\argv[2] = 4 & fourbits("2r" || argv[2])), c)
write(t1, " + ", t2, " = ", c.c, ":", \cli) & return
# if no result for that, try decimal values
cli := fourbitadder(t1 := fourbits(\argv[1]),
t2 := fourbits(\argv[2]), c)
write(t1, " + ", t2, " = ", c.c, ":", \cli) & return
# or display the help
write("Usage: 4bitadder [\"test\"] | [bbbb bbbb] | [n n], range 0-15")
end
#
# integer to fourbits as string
#
procedure fourbits(i)
local s, t
if not numeric(i) then fail
if not (0 <= integer(i) < 16) then {
write("out of range: ", i)
fail
}
s := ""
every t := (8 | 4 | 2 | 1) do {
s ||:= if iand(i, t) ~= 0 then "1" else "0"
}
return s
end
#
# low level xor emulation with or, and, not
#
procedure xor(a, b)
return ior(iand(a, icom(b)), iand(b, icom(a)))
end
#
# half adder, and into carry, xor for result bit
#
procedure halfadder(a, b, carry)
carry.c := iand(a,b)
return xor(a,b)
end
#
# full adder, two half adders, or for carry
#
procedure fulladder(a, b, c0, c1)
local c2, c3, r
c2 := carry(0)
c3 := carry(0)
# connect two half adders with carry
r := halfadder(halfadder(c0.c, a, c2), b, c3)
c1.c := ior(c2.c, c3.c)
return r
end
#
# fourbit adder, as bit string
#
procedure fourbitadder(a, b, cr)
local cs, c0, c1, c2, s
cs := carry(0)
c0 := carry(0)
c1 := carry(0)
c2 := carry(0)
# create a string for subscripting. strings are immutable, new strings created
s := "0000"
# bit 0 is string position 4
s[4+:1] := fulladder(a[4+:1], b[4+:1], cs, c0)
s[3+:1] := fulladder(a[3+:1], b[3+:1], c0, c1)
s[2+:1] := fulladder(a[2+:1], b[2+:1], c1, c2)
s[1+:1] := fulladder(a[1+:1], b[1+:1], c2, cr)
# cr.c is the overflow carry
return s
end
|
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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
A burning cell turns into an empty cell
A tree will burn if at least one neighbor is burning
A tree ignites with probability f even if no neighbor is burning
An empty space fills with a tree with probability p
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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
lastzp = $38
tablelo = $5000
tablehi = tablelo+25
JSR START
STA V2
LDA #$4C ; JMP instruction
STA SEED2 ; temporary JMP
LDX #$00 ; y coord
table:
TXA
JSR SEED2 ; temporary JMP GBASCALC
LDA GBASL
STA tablelo,X
LDA GBASH
STA tablehi,X
LDY #$00
TYA
clrline:
STA (GBASL),Y
INY
CPY #40
BNE clrline
INX
CPX V2
BNE table
JSR sseed0
JSR sseed2
LDX #$60
STX PAGE
STX TOPH
LDY #$00
STY TOPL
TYA
zero: STA (TOPL),Y
INY
BNE zero
INX
STX TOPH
CPX #$80
BNE zero
loop3:
LDX #0
STX TOPL
LDA #41
STA MIDL
STA PLOTL
LDA #83
STA BTML
LDA PAGE
STA TOPH
STA MIDH
STA BTMH
EOR #$10
STA PLOTH
STA PAGE
loop2:
TXA
STX V2
LSR ; F800 PLOT-like...
; PHP ; F801
TAY ; save A in Y without touching C
LDA #$0F
BCC over2
ADC #$E0
over2: STA PLOTC ; PLOT...
LDA tablelo,Y ; lookup instead of GBASCALC
STA GBASL
LDA tablehi,Y
STA GBASH
; PLP ; continue PLOT
LDY #$01 ; x coord
loop1:
STY H2
LDA (MIDL),Y
STA (PLOTL),Y
BEQ empty
BPL tree
LDA #EMPTY2
doplot: LDY H2
STA (PLOTL),Y
DEY
EOR (GBASL),Y
AND PLOTC
EOR (GBASL),Y
STA (GBASL),Y
noplot:
LDY H2
INY
CPY #41
BNE loop1
LDA MIDL
STA TOPL
LDA MIDH
STA TOPH
LDA BTML
STA MIDL
STA PLOTL
CLC
ADC #42
STA BTML
LDA BTMH
EOR #$10
STA PLOTH
EOR #$10
STA MIDH
ADC #$00
STA BTMH
LDX V2
INX
CPX #48
BNE loop2
JSR QUIT
JMP loop3
empty:
DEC SEED2
BNE noplot
JSR sseed2 ; probability f
LDA #TREE2
BNE doplot
ignite:
LDA #FIRE2
BNE doplot
tree:
DEC SEED0
BNE check
DEC SEED1
BNE check
JSR sseed0 ; probability p
BNE ignite
check:
LDA (TOPL),Y ; n
ORA (BTML),Y ; s
DEY
ORA (TOPL),Y ; nw
ORA (MIDL),Y ; w
ORA (BTML),Y ; sw
INY
INY
ORA (TOPL),Y ; ne
ORA (MIDL),Y ; e
ORA (BTML),Y ; se
BMI ignite
BPL noplot
sseed0:
LDA #$17 ; 1 in 10007 (prime)
STA SEED0
LDA #$27
STA SEED1
RTS
sseed2:
LDA #$65 ; 1 in 101 (prime)
STA SEED2
RTS
default:
LDA #<GBASCALC ; setup GBASCALC
STA SEED0
LDA #>GBASCALC
STA SEED1
LDA #25 ; screen rows
RTS
GBASCALC:
LDY #$00
STY GBASH
ASL
ASL
ASL
STA GBASL
ASL
ROL GBASH
ASL
ROL GBASH
ADC GBASL
STA GBASL
LDA GBASH
ADC #$04
STA GBASH
RTS
QUIT:
LDA $E000
; APPLE II
CMP #$4C
BNE c64quit
BIT $C000 ; apple ii keypress?
BPL CONTINUE ; no keypressed then continue
BIT $C010 ; clear keyboard strobe
BIT $C051 ; text mode
; end APPLE II specific
ABORT:
PLA
PLA
LDX #GBASL
restorzp:
LDA $5100,X
STA $00,X
INX
CPX #lastzp
BNE restorzp
CONTINUE:
RTS
START:
LDX #GBASL
savezp:
LDA $00,X
STA $5100,X
INX
CPX #lastzp
BNE savezp
; machine ???
LDA $E000 ; terribly unreliable, oh well
; APPLE II
CMP #$4C ; apple ii?
BNE c64start ; nope, try another
BIT $C056 ; low resolution
BIT $C052 ; full screen
BIT $C054 ; page one
BIT $C050 ; graphics
; GBASCALC = $F847
LDA #$47
STA SEED0
LDA #$F8
STA SEED1
LDA #24 ; screen rows
RTS
; end APPLE II specific
; COMMODORE 64 specific
c64quit:
; COMMODORE 64
CMP #$85 ; commodore 64?
BNE CONTINUE ; nope, default to no keypress
LDA $C6 ; commodore keyboard buffer length
BEQ CONTINUE ; no keypressed then continue
LDA #$00
STA $C6
LDA $D016 ; Screen control register #2
AND #$EF ; Bit #4: 0 = Multicolor mode off.
STA $D016
LDA #21 ; default character set
STA $D018
BNE ABORT
c64start:
CMP #$85 ; commodore 64?
BEQ c64yes ; yes
JMP default ; no, default to boringness
c64yes:
LDA #$00 ; black
STA $D020 ; border
LDA #$00 ; black
STA $D021 ; background
LDA #$05 ; dark green
STA $D022 ; Extra background color #1
LDA #$08 ; orange
STA $D023 ; Extra background color #2
LDA $D016 ; Screen control register #2
ORA #$10 ; Bit #4: 1 = Multicolor mode on.
STA $D016
LDA #$30 ; 0011 0000 $3000 charset page
STA PLOTH
LSR
LSR
STA PLOTC ; 0000 1100 #$0C
; 53272 $D018
; POKE 53272,(PEEK(53272)AND240)+12: REM SET CHAR POINTER TO MEM. 12288
; Bits #1-#3: In text mode, pointer to character memory
; (bits #11-#13), relative to VIC bank, memory address $DD00
; %110, 6: $3000-$37FF, 12288-14335.
LDA $D018
AND #$F0
ORA PLOTC
STA $D018
; setup nine characters
; 00- 00 00
LDA #$00 ; chr(0) * 8
STA PLOTL
; --- LDA #$00 ; already zero
TAX ; LDX #$00
JSR charset
; 04- 00 55
LDA #32 ; chr(4) * 8
STA PLOTL
LDA #$55
; LDX #$00 ; already zero
JSR charset
; 09- 00 AA
LDA #72 ; chr(9) * 8
STA PLOTL
LDA #$AA
; LDX #$00 ; already zero
JSR charset
; 40- 55 00
LDA PLOTH ; 512 = chr(64) * 8
CLC
ADC #$02
STA PLOTH
LDX #$00
STX PLOTL
LDA #$00
LDX #$55
JSR charset
; 44- 55 55
LDA #32 ; chr(68) * 8
STA PLOTL
TXA ; LDA #$55
; LDX #$55 ; already 55
JSR charset
; 49- 55 AA
LDA #72 ; chr(73) * 8
STA PLOTL
LDA #$AA
; LDX #$55 ; already 55
JSR charset
; 90- AA 00
LDA PLOTH ; chr(144) * 8
CLC
ADC #$02
STA PLOTH
LDA #128
STA PLOTL
LDA #$00
LDX #$AA
JSR charset
; 94- AA 55
LDA #160 ; chr(148) * 8
STA PLOTL
LDA #$55
; LDX #$AA ; already AA
JSR charset
; 99- AA AA
LDA #200 ; chr(153) * 8
STA PLOTL
TXA ; LDA #$AA
; LDX #$AA ; already AA
JSR charset
JMP default
charset:
LDY #$00
chartop:
STA (PLOTL),Y
INY
CPY #$04
BNE chartop
TXA
charbtm:
STA (PLOTL),Y
INY
CPY #$08
BNE charbtm
RTS
; end COMMODORE 64 specific
|
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 arrays.
if (typeof input[i]=="object") {
output=output.concat(flatten(input[i]));
} else {
output.push(input[i]);
}
}
return output;
}
|
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 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#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],0 ; Command line empty?
je printusage ; Then print usage and stop
mov al,[argstart] ; Get first byte on command line
cmp al,'3' ; <3?
jb printusage ; Then print usage and stop
cmp al,'8' ; >8?
ja printusage ; Then print usage and stop
sub al,'0' ; Make number from ASCII
mov [boardsz],al ; Store the board size
mov ah,puts ; If we made it here, print the
mov dx,welcome ; welcome banner.
int 21h
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Generate random board
call xabcinit ; Initialize the RNG with system time
mov si,board
xor bx,bx
genboard: call xabcrand ; Get random byte
mov ah,al
call xabcrand ; Get another
and ax,0101h ; Keep only the low bit of each byte
mov [si+bx],ax ; And store them
inc bx ; Two bytes onward
inc bx
cmp bl,64 ; Are we done?
jne genboard
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copy the board into the goal
mov si,board ; Source is board
mov di,goal ; Destination is goal
mov bx,0 ; Start at the beginning
copyboard: mov ax,[si+bx] ; Load word from board
mov [di+bx],ax ; Store word in goal
inc bx ; We've copied two bytes
inc bx
cmp bl,64 ; Are we done yet?
jne copyboard
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Make an amount of random flips
call xabcrand ; Random number
and al,15 ; [0..15]
add al,5 ; [5..20]
mov [sysflips],al ; Store in memory
mov cl,al ; Flip doesn't touch CL
xor ch,ch ; Set high byte zero
randflips: call xabcrand ; Random number
call flip ; Do a flip (unused bits are ignored)
loop randflips
mov byte [usrflips],0 ; Initialize user flips to 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print game status (moves, goal moves)
status: mov ah,puts
mov dx,smoves
int 21h
mov al,[usrflips]
call printal
mov ah,puts
mov dx,sgoal
int 21h
mov al,[sysflips]
call printal
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the game board and goal board
mov ah,puts ; Print the header
mov dx,sboardhdr
int 21h
mov cl,2 ; Print two headers
mov ah,putch ; Indent columns
;;; Print column headers
colheader: mov dl,' '
int 21h
int 21h
mov bh,0 ; Offset
mov bl,'A' ; First letter
.curcol: cmp bh,[boardsz]
mov dl,bl ; Print letter
jb .printcol
mov dl,' ' ; Print space if column not used
.printcol: call dlspace ; Print DL + separator space
inc bl
inc bh
cmp bh,8 ; Done yet?
jb .curcol
mov dl,9 ; Separate the boards with a TAB
int 21h
dec cl ; We need two headers (board and goal)
jnz colheader
mov ah,puts ; Print a newline afterwards
mov dx,newline
int 21h
;;; Print the rows of the boards
xor bh,bh ; Zero high byte of BX
xor cl,cl ; Row index
boardrow: mov ch,2 ; Two rows, board and goal
mov si,board ; Start by printing the game board
.oneboard: xor dh,dh ; Column index
mov dl,cl ; Print row number
add dl,'1'
call dlspace
.curpos: cmp dh,[boardsz] ; Column in use?
mov dl,' ' ; If not, print a space
jae .printpos
mov bl,cl ; Row index
shl bl,1 ; * 8
shl bl,1
shl bl,1
add bl,dh ; Add column index
mov dl,[bx+si] ; Get position from board
add dl,'0' ; Print as ASCII 0 or 1
.printpos: call dlspace
inc dh ; Increment column index
cmp dh,8 ; Are we there yet?
jb .curpos ; If not, print next position
mov dl,9 ; Separate the boards with a TAB
int 21h
dec ch ; Have we printed the goal yet?
mov si,goal ; If not, print the goal next
jnz .oneboard
mov ah,puts ; Print a newline
mov dx,newline
int 21h
inc cl ; Next row
cmp cl,[boardsz] ; Are we there yet?
jb boardrow ; If not, print the next row.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Ask the user for a move
mov ah,puts ; Write the prompt
mov dx,prompt
int 21h
readmove: mov ah,getch ; Read a character
int 21h
or al,32 ; Make letters lowercase
cmp al,'q' ; Quit?
je quit
cmp al,'9' ; Numeric (row) input?
jbe .nummove ; If not, alphabetic (column) input
;;; Letter input (column)
sub al,'a' ; Subtract 'a'
jc invalid ; If it was <'a', invalid input
cmp al,[boardsz] ; Is it on the board?
jae invalid
or al,128 ; Set high bit, for column flip
call flip ; Flip the column
jmp checkwin ; See if the user has won
;;; Number input (row)
.nummove: sub al,'1' ; Rows start at 1.
jc invalid ; If <'1', then invalid
cmp al,[boardsz] ; Is it on the board?
jae invalid
call flip ; Flip the row
;;; Check if the user has won the game
checkwin: xor bh,bh ; Zero high byte of array index
mov dl,[boardsz]
xor ch,ch ; Row coordinate
.row: xor cl,cl ; Column coordinate
.pos: mov bl,ch ; BL = row*8 + col
shl bl,1
shl bl,1
shl bl,1
add bl,cl
mov al,[board+bx] ; Get position from board
cmp al,[goal+bx] ; Compare with corresponding goal pos
jne .nowin ; Not equal: the user hasn't won
inc cl
cmp cl,dl ; Done all positions on row?
jb .pos ; If not, do next.
inc ch
cmp ch,dl ; Done all rows?
jb .row ; If not, do next.
;;; If we get here, the user has won
mov ah,puts
mov dx,win
int 21h
ret
;;; The user hasn't won
.nowin: inc byte [usrflips] ; Record that the user has made a move
jmp status ; Print status and board, get new move
;;; Invalid input
invalid: mov ah,puts
mov dx,nope
int 21h
jmp readmove
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Flip the line or column in AL. If bit 7 set, flip column.
flip: mov si,board ; SI = board
test al,al ; This sets sign flag if bit 7 set
js .column ; If so, flip column.
and al,7 ; We only need the first 3 bits
shl al,1 ; Multiply by 8
shl al,1 ; 8086 does not support 'shl al,3'
shl al,1
xor ah,ah ; High byte 0
mov bx,ax ; BX = offset
mov ah,4 ; 4 words
.rowloop xor word [si+bx],0101h ; Flip two bytes at once
inc bx
inc bx
dec ah
jnz .rowloop
ret
.column: and al,7 ; Flip a column.
xor ah,ah
mov bx,ax ; BX = row offset
mov ah,8 ; 8 bytes (need to do it byte by byte)
.colloop: xor byte [si+bx],01h ; Flip position
add bx,8
dec ah
jnz .colloop
quit: ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print usage and stop
printusage: mov ah,puts
mov dx,usage
int 21h
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the character in DL followed by a space
dlspace: mov ah,putch
int 21h
mov dl,' '
int 21h
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Initialize the random number generator using the system
;;; time.
xabcinit: mov ah,time
int 21h
mov bx,xabcdat
xor [bx],cx
xor [bx+2],dx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The "X ABC" random number generator
;;; Return random byte in AL
xabcrand: push bx ; Save registers
push cx
push dx
mov bx,xabcdat ; RNG state pointer
mov cx,[bx] ; CL=x CH=a
mov dx,[bx+2] ; DL=b DH=c
inc cl ; X++
xor ch,dh ; A^=C
xor ch,cl ; A^=X
add dl,ch ; B+=A
mov al,dl
shr al,1 ; B>>1
xor al,ch ; ^A
add al,dh ; +C
mov dh,al ; ->C
mov [bx],cx ; Store new RNG state
mov [bx+2],dx
pop dx ; Restore registers
pop cx
pop bx
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print the byte in AL as a decimal number
printal: mov di,decnum + 3 ; Room in memory for decimal number
mov dl,10 ; Divide by 10
.loop: xor ah,ah ; Zero remainder
div dl ; Divide by 10
add ah,'0' ; Add ASCII 0 to remainder
dec di
mov [di],ah ; Store digit in memory
and al,al ; Done yet?
jnz .loop ; If not, next digit
mov dx,di ; DX = number string
mov ah,puts ; Print the string
int 21h
ret
section .data
decnum: db '***$' ; Decimal number placeholder
usage: db 'Usage: FLIP [3..8], number is board size.$'
welcome: db '*** FLIP THE BITS *** ',13,10
db '--------------------- ',
newline: db 13,10,'$'
smoves: db 13,10,13,10,'Your flips: $'
sgoal: db 9,'Goal: $'
sboardhdr: db 13,10,10,'--Board------------'
db 9,'--Goal-------------',13,10,'$'
prompt: db 13,10,'Press line or column to flip, or Q to quit: $'
nope: db 8,32,8,7,'$' ; Beep and erase input
win: db 13,10,7,7,7,'You win!$'
section .bss
boardsz: resb 1 ; Board size
sysflips: resb 1 ; Amount of flips that the system does
usrflips: resb 1 ; Amount of flips that the user does
xabcdat: resb 4 ; Four byte RNG state
board: resb 64 ; 8*8 board
goal: resb 64 ; 8*8 goal
|
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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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.
;The program counter is copied to the link register, then the operand of this command becomes the new program counter.
BX Rn ;Branch and Exchange. The operand is a register. The program counter is swapped with the register specified.
;BX LR is commonly used to return from a subroutine.
addeq R0,R0,#1 ;almost any instruction can be made conditional. If the flag state doesn't match the condition code, the instruction
;has no effect on registers or memory.
|
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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#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",
16 to "sixteen",
17 to "seventeen",
18 to "eighteen",
19 to "nineteen",
20 to "twenty",
30 to "thirty",
40 to "forty",
50 to "fifty",
60 to "sixty",
70 to "seventy",
80 to "eighty",
90 to "ninety"
)
val bigNames = mapOf(
1_000L to "thousand",
1_000_000L to "million",
1_000_000_000L to "billion",
1_000_000_000_000L to "trillion",
1_000_000_000_000_000L to "quadrillion",
1_000_000_000_000_000_000L to "quintillion"
)
fun numToText(n: Long): String {
if (n == 0L) return "zero"
val neg = n < 0L
val maxNeg = n == Long.MIN_VALUE
var nn = if (maxNeg) -(n + 1) else if (neg) -n else n
val digits3 = IntArray(7)
for (i in 0..6) { // split number into groups of 3 digits from the right
digits3[i] = (nn % 1000).toInt()
nn /= 1000
}
fun threeDigitsToText(number: Int) : String {
val sb = StringBuilder()
if (number == 0) return ""
val hundreds = number / 100
val remainder = number % 100
if (hundreds > 0) {
sb.append(names[hundreds], " hundred")
if (remainder > 0) sb.append(" ")
}
if (remainder > 0) {
val tens = remainder / 10
val units = remainder % 10
if (tens > 1) {
sb.append(names[tens * 10])
if (units > 0) sb.append("-", names[units])
}
else sb.append(names[remainder])
}
return sb.toString()
}
val strings = Array<String>(7) { threeDigitsToText(digits3[it]) }
var text = strings[0]
var big = 1000L
for (i in 1..6) {
if (digits3[i] > 0) {
var text2 = strings[i] + " " + bigNames[big]
if (text.length > 0) text2 += " "
text = text2 + text
}
big *= 1000
}
if (maxNeg) text = text.dropLast(5) + "eight"
if (neg) text = "negative " + text
return text
}
fun fourIsMagic(n: Long): String {
if (n == 4L) return "Four is magic."
var text = numToText(n).capitalize()
val sb = StringBuilder()
while (true) {
val len = text.length.toLong()
if (len == 4L) return sb.append("$text is four, four is magic.").toString()
val text2 = numToText(len)
sb.append("$text is $text2, ")
text = text2
}
}
fun main(args: Array<String>) {
val la = longArrayOf(0, 4, 6, 11, 13, 75, 100, 337, -164, 9_223_372_036_854_775_807L)
for (i in la) {
println(fourIsMagic(i))
println()
}
}
|
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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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 entrada:\n"
Do While Not Eof(1)
Line Input #1, linea 'lee una linea
Print linea 'imprime por pantalla esa linea
For i As Integer = longRegistro To 1 Step -1
Print #2, Chr(Asc(linea, i)); 'escribe el inverso de la linea
Next i
Print #2, Chr(13);
Loop
Close #1, #2
Dim As Integer a
Open archivoSalida For Input As #2
Print !"\nDatos de salida:\n"
Do While Not Eof(2)
Line Input #2, linea
For j As Integer = 0 To Len(linea)-1
Print Chr(linea[j]);
a += 1: If a = longRegistro Then a = 0 : Print Chr(13)
Next j
Loop
Close
Sleep
|
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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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 entrada:\n"
Do While Not Eof(1)
Line Input #1, linea 'lee una linea
Print linea 'imprime por pantalla esa linea
For i As Integer = longRegistro To 1 Step -1
Print #2, Chr(Asc(linea, i)); 'escribe el inverso de la linea
Next i
Print #2, Chr(13);
Loop
Close #1, #2
Dim As Integer a
Open archivoSalida For Input As #2
Print !"\nDatos de salida:\n"
Do While Not Eof(2)
Line Input #2, linea
For j As Integer = 0 To Len(linea)-1
Print Chr(linea[j]);
a += 1: If a = longRegistro Then a = 0 : Print Chr(13)
Next j
Loop
Close
Sleep
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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++) {
dist[i, j] = double.PositiveInfinity;
}
}
for (int i = 0; i < weights.GetLength(0); i++) {
dist[weights[i, 0] - 1, weights[i, 1] - 1] = weights[i, 2];
}
int[,] next = new int[numVerticies, numVerticies];
for (int i = 0; i < numVerticies; i++) {
for (int j = 0; j < numVerticies; j++) {
if (i != j) {
next[i, j] = j + 1;
}
}
}
for (int k = 0; k < numVerticies; k++) {
for (int i = 0; i < numVerticies; i++) {
for (int j = 0; j < numVerticies; j++) {
if (dist[i, k] + dist[k, j] < dist[i, j]) {
dist[i, j] = dist[i, k] + dist[k, j];
next[i, j] = next[i, k];
}
}
}
}
PrintResult(dist, next);
}
static void PrintResult(double[,] dist, int[,] next) {
Console.WriteLine("pair dist path");
for (int i = 0; i < next.GetLength(0); i++) {
for (int j = 0; j < next.GetLength(1); j++) {
if (i != j) {
int u = i + 1;
int v = j + 1;
string path = string.Format("{0} -> {1} {2,2:G} {3}", u, v, dist[i, j], u);
do {
u = next[u - 1, v - 1];
path += " -> " + u;
} while (u != v);
Console.WriteLine(path);
}
}
}
}
static void Main(string[] args) {
int[,] weights = { { 1, 3, -2 }, { 2, 1, 4 }, { 2, 3, 3 }, { 3, 4, 2 }, { 4, 2, -1 } };
int numVerticies = 4;
FloydWarshall(weights, numVerticies);
}
}
}
|
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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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,_
23, 29, 31, 37, 41, 43, 47, 53}
dim as uinteger i
dim as uinteger ptr b = forward_difference( a() )
for i = 0 to ubound(a)-1
print *(b+i)
next i
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
A burning cell turns into an empty cell
A tree will burn if at least one neighbor is burning
A tree ignites with probability f even if no neighbor is burning
An empty space fills with a tree with probability p
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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 paragraphs
;;; Field values
EMPTY: equ 0 ; Empty cell (also CGA black)
TREE: equ 1 ; Tree cell (also CGA green)
FIRE: equ 2 ; Burning cell (also CGA red)
;;; MS-DOS system calls and values
TOPSEG: equ 2 ; First unavailable segment
puts: equ 9 ; Print a string
time: equ 2Ch ; Get system time
exit: equ 4Ch ; Exit to DOS
;;; BIOS calls and values
palet: equ 0Bh ; Set CGA color pallette
vmode: equ 0Fh ; Get current video mode
keyb: equ 1 ; Get keyboard status
CGALO: equ 4 ; Low-res (4-color) CGA graphics mode
MDA: equ 7 ; MDA monochrome text mode
CGASEG: equ 0B800h ; CGA memory segment
cpu 8086
org 100h
section .text
;;; Program set-up (check memory size and set video mode)
mov sp,stack.top ; Move stack inwards
mov bp,sp ; Set BP to first available paragraph
mov cl,4
shr bp,cl
inc bp
mov dx,cs
add bp,dx
mov bx,[TOPSEG] ; Get first unavailable segment
sub bx,bp ; Get amount of available memory
cmp bx,FPARA*2 ; Enough to fit two fields?
ja mem_ok
mov dx,errmem ; If not, print error message
err: mov ah,puts
int 21h
mov ah,exit ; And stop
int 21h
mem_ok: mov ah,vmode ; Get current video mode
int 10h
push ax ; Keep on stack for later retrieval
cmp al,MDA ; MDA card does not support CGA graphics,
mov dx,errcga ; so print an error and quit.
je err
mov ax,CGALO ; Otherwise, switch to 320x200 CGA mode
int 10h
mov ah,palet ; And set the black/green/red/brown palette
mov bx,0100h
int 10h
mov ah,time ; Get the system time
int 21h
mov [rnddat],cx ; Use it as the RNG seed
mov [rnddat+2],dx
;;; Initialize the field (place trees randomly)
mov es,bp ; ES = field segment
xor di,di ; Start at first field
mov cx,FSIZE ; CX = how many cells to initialize
mov ah,TREE
ptrees: call random ; Get random byte
and al,ah ; Place a tree 50% of the time
stosb
loop ptrees
mov ds,bp ; DS = field segment
;;; Write field to CGA display
disp: xor si,si ; Start at beginning
mov dx,CGASEG ; ES = CGA memory segment
.scrn: mov es,dx
xor di,di ; Start of segment
.line: mov cx,HSIZE/8 ; 8 pixels per word
.word: xor bx,bx ; BX will hold CGA word
xor ah,ah ; Set high byte to zero
%rep 7 ; Unroll this loop for speed
lodsb ; Get cell
or bx,ax ; Put it in low 2 bits of BX
shl bx,1 ; Shift BX to make room for next field
shl bx,1
%endrep
lodsb ; No shift needed for final cell
or ax,bx
stosw ; Store word in CGA memory
loop .word ; Do next byte of line
add si,HSIZE ; Even and odd lines stored separately
cmp si,FSIZE ; Done yet?
jb .line ; If not, do next line
add dx,200h ; Move to next segment
cmp dx,CGASEG+200h ; If we still need to do the odd lines,
mov si,HSIZE ; then do them
jbe .scrn
;;; Stop the program if a key is pressed
mov ah,1 ; Check if a key is pressed
int 16h
jz calc ; If not, calculate next field state
pop ax ; Otherwise, restore the old video mode,
cbw
int 10h
mov ah,exit ; and exit to DOS.
int 21h
;;; Calculate next field state
calc: mov ax,ds ; Set ES = new field segment
add ax,FPARA
mov es,ax
xor di,di ; Start at beginning
xor si,si
.cell: lodsb ; Get cell
dec al ; A=1 = tree
jz .tree
dec al ; A=2 = fire
jz .fire
call rand16 ; An empty space fills with a tree
cmp ax,probP ; with probability P.
jc .mtree ; Otherwise it stays empty
.fire: xor al,al ; A burning tree turns into an empty cell
stosb
jmp .cnext
.mtree: mov al,TREE
stosb
.cnext: cmp si,FSIZE ; Are we there yet?
jne .cell ; If not, do next cell
push es ; Done - set ES=old field, DS=new field,
push ds
pop es
pop ds
mov cx,FSIZE/2
xor si,si
xor di,di
rep movsw ; copy the new field to the old field,
push es ; set DS to be the field to draw,
pop ds
xor di,di ; Instead of doing edge case handling in the
xor ax,ax ; Moore neighbourhood calculation, just zero
mov cx,HSIZE/2 ; out the borders for a slightly smaller image
rep stosw ; Upper border,
mov di,FSIZE-HSIZE
mov cx,HSIZE/2
rep stosw ; lower border,
mov di,HSIZE-5 ; right border.
mov cx,VSIZE-1
.bordr: stosb
add di,HSIZE-1
loop .bordr
jmp disp ; and update the display.
.tree: mov ax,[si-HSIZE-2] ; Load Moore neighbourhood
or al,[si-HSIZE]
or ax,[si-2]
or al,[si]
or ax,[si+HSIZE-2]
or al,[si+HSIZE]
or al,ah
test al,FIRE ; Are any of the trees on fire?
jnz .tburn ; Then set this tree on fire too
call rand16 ; Otherwise, spontaneous combustion?
cmp ax,probF
jc .tburn
mov al,TREE ; If not, the tree remains a tree
stosb
jmp .cnext
.tburn: mov al,FIRE ; Set the tree on fire
stosb
jmp .cnext
;;; Get a random word in AX
rand16: call random
xchg al,ah
;;; Get a random byte in AL. BX and DX destroyed.
random: mov bx,[cs:rnddat] ; BL=X BH=A
mov dx,[cs:rnddat+2] ; DL=B DH=C
inc bl ; X++
xor bh,dh ; A ^= C
xor bh,bl ; A ^= X
add dl,bh ; B += A
mov al,dl ; C' = B
shr al,1 ; C' >>= 1
add al,dh ; C' += C
xor al,bh ; C' ^= A
mov dh,al ; C = C'
mov [cs:rnddat+2],dx ; Update RNG state
mov [cs:rnddat],bx
ret
section .data
errcga: db 'CGA mode not supported.$'
errmem: db 'Not enough memory.$'
section .bss
rnddat: resb 4 ; RNG state
stack: resw 128 ; Stack space
.top: equ $
|
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 Kind is
when Data_Node =>
Data : Element_Type;
when List_Node =>
Sublist : List;
end case;
end record;
procedure Append (L : in out List; E : Element_Type);
procedure Append (L : in out List; N : List);
function Flatten (L : List) return List;
function New_List (E : Element_Type) return List;
function New_List (N : List) return List;
function To_String (L : List) return String;
end Nestable_Lists;
|
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 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#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(x+y*side))
OD
OD
RETURN
PROC Randomize(BYTE ARRAY board BYTE len)
BYTE i
FOR i=0 TO len-1
DO
board(i)=Rand(2)
OD
RETURN
BYTE FUNC Solved(BYTE ARRAY goal,board BYTE side)
BYTE i,len
len=side*side
FOR i=0 TO len-1
DO
IF goal(i)#board(i) THEN
RETURN (0)
FI
OD
RETURN (1)
PROC FlipRow(BYTE ARRAY board BYTE side,row)
BYTE i,ind
IF row>=side THEN RETURN FI
FOR i=0 TO side-1
DO
ind=i+row*side
board(ind)=1-board(ind)
OD
UpdateBoard(board,side,boardX,boardY)
RETURN
PROC FlipColumn(BYTE ARRAY board BYTE side,column)
BYTE i,ind
IF column>=side THEN RETURN FI
FOR i=0 TO side-1
DO
ind=column+i*side
board(ind)=1-board(ind)
OD
UpdateBoard(board,side,boardX,boardY)
RETURN
PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC UpdateStatus(BYTE ARRAY goal,board BYTE side)
Position(9,3) Print("Game status: ")
IF Solved(goal,board,side) THEN
Print("SOLVED !")
Sound(0,100,10,5) Wait(5)
Sound(0,60,10,5) Wait(5)
Sound(0,40,10,5) Wait(5)
Sound(0,0,0,0)
ELSE
Print("Shuffled")
FI
RETURN
PROC Init(BYTE ARRAY goal,board BYTE side)
BYTE size,i,n
size=side*side
Randomize(goal,size)
MoveBlock(board,goal,size)
UpdateBoard(goal,side,goalX,boardY)
WHILE Solved(goal,board,side)
DO
FOR i=1 TO 20
DO
n=Rand(side)
IF Rand(2)=0 THEN
FlipRow(board,side,n)
ELSE
FlipColumn(board,side,n)
FI
OD
OD
RETURN
PROC Main()
DEFINE SIDE="3"
DEFINE SIZE="9"
BYTE ARRAY board(SIZE),goal(SIZE)
BYTE CRSINH=$02F0 ;Controls visibility of cursor
BYTE k,CH=$02FC ;Internal hardware value for last key pressed
Graphics(0)
SetColor(2,0,2)
CRSINH=1 ;hide cursor
Position(boardX,boardY-2) Print("Board")
Position(goalX+1,boardY-2) Print("Goal")
Position(9,19) Print("Space bar - shuffle")
Init(goal,board,SIDE)
UpdateStatus(goal,board,side)
DO
k=CH
IF k#$FF THEN
CH=$FF
IF k=31 THEN FlipRow(board,SIDE,0)
ELSEIF k=30 THEN FlipRow(board,SIDE,1)
ELSEIF k=26 THEN FlipRow(board,SIDE,2)
ELSEIF k=63 THEN FlipColumn(board,SIDE,0)
ELSEIF k=21 THEN FlipColumn(board,SIDE,1)
ELSEIF k=18 THEN FlipColumn(board,SIDE,2)
ELSEIF k=33 THEN Init(goal,board,SIDE) FI
UpdateStatus(goal,board,SIDE)
FI
OD
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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#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 first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#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", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }
local lionlist = { [0]="", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion" }
local abs, floor = math.abs, math.floor
local function numname(num)
if (num == 0) then return "zero" end
local absnum, lion, result = abs(num), 0, ""
local function dashed(s) return s=="" and s or "-"..s end
local function spaced(s) return s=="" and s or " "..s end
while (absnum > 0) do
local word, ones, tens, huns = "", absnum%10, floor(absnum/10)%10, floor(absnum/100)%10
if (tens==0) then word = oneslist[ones]
elseif (tens==1) then word = teenlist[ones]
else word = tenslist[tens] .. dashed(oneslist[ones]) end
if (huns > 0) then word = oneslist[huns] .. " hundred" .. spaced(word) end
if (word ~= "") then result = word .. spaced(lionlist[lion]) .. spaced(result) end
absnum = floor(absnum / 1000)
lion = lion + 1
end
if (num < 0) then result = "negative " .. result end
return result
end
local function fourismagic(num)
local function fim(num)
local name = numname(num)
if (num == 4) then
return name .. " is magic."
else
local what = numname(#name)
return name .. " is " .. what .. ", " .. fim(#name)
end
end
local result = fim(num):gsub("^%l", string.upper)
return result
end
local numbers = { -21,-1, 0,1,2,3,4,5,6,7,8,9, 12,34,123,456,1024,1234,12345,123456,1010101 }
for _, num in ipairs(numbers) do
print(num, fourismagic(num))
end
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#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(‘ ’))
pfloyd(floyd(5))
pfloyd(floyd(14))
|
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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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 entrada:\n"
Do While Not Eof(1)
Line Input #1, linea 'lee una linea
Print linea 'imprime por pantalla esa linea
For i As Integer = longRegistro To 1 Step -1
Print #2, Chr(Asc(linea, i)); 'escribe el inverso de la linea
Next i
Print #2, Chr(13);
Loop
Close #1, #2
Dim As Integer a
Open archivoSalida For Input As #2
Print !"\nDatos de salida:\n"
Do While Not Eof(2)
Line Input #2, linea
For j As Integer = 0 To Len(linea)-1
Print Chr(linea[j]);
a += 1: If a = longRegistro Then a = 0 : Print Chr(13)
Next j
Loop
Close
Sleep
|
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, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
Task
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length.
Sample data
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size.
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 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block
prompt$ dd if=infile.dat cbs=80 conv=unblock
Bonus round
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
|
#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, err := os.Open("infile.dat")
check(err)
defer in.Close()
out, err := os.Create("outfile.dat")
check(err)
record := make([]byte, 80)
empty := make([]byte, 80)
for {
n, err := in.Read(record)
if err != nil {
if n == 0 {
break // EOF reached
} else {
out.Close()
log.Fatal(err)
}
}
reverseBytes(record)
out.Write(record)
copy(record, empty)
}
out.Close()
// Run dd from within program to write output.dat
// to standard output as normal text with newlines.
cmd := exec.Command("dd", "if=outfile.dat", "cbs=80", "conv=unblock")
bytes, err := cmd.Output()
check(err)
fmt.Println(string(bytes))
}
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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 != j) {
auto u = i + 1;
auto v = j + 1;
std::cout << "(" << u << " -> " << v << ", " << dist[i][j]
<< ", ";
std::stringstream path;
path << u;
do {
u = next[u - 1][v - 1];
path << " -> " << u;
} while (u != v);
std::cout << path.str() << ")" << std::endl;
}
}
}
}
void solve(std::vector<std::vector<int>> w_s, const int num_vertices) {
std::vector<std::vector<double>> dist(num_vertices);
for (auto& dim : dist) {
for (auto i = 0; i < num_vertices; ++i) {
dim.push_back(INT_MAX);
}
}
for (auto& w : w_s) {
dist[w[0] - 1][w[1] - 1] = w[2];
}
std::vector<std::vector<int>> next(num_vertices);
for (auto i = 0; i < num_vertices; ++i) {
for (auto j = 0; j < num_vertices; ++j) {
next[i].push_back(0);
}
for (auto j = 0; j < num_vertices; ++j) {
if (i != j) {
next[i][j] = j + 1;
}
}
}
for (auto k = 0; k < num_vertices; ++k) {
for (auto i = 0; i < num_vertices; ++i) {
for (auto j = 0; j < num_vertices; ++j) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
next[i][j] = next[i][k];
}
}
}
}
print(dist, next);
}
int main() {
std::vector<std::vector<int>> w = {
{ 1, 3, -2 },
{ 2, 1, 4 },
{ 2, 3, 3 },
{ 3, 4, 2 },
{ 4, 2, -1 },
};
int num_vertices = 4;
solve(w, num_vertices);
std::cin.ignore();
std::cin.get();
return 0;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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(a)-ord]
}
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
// Create AND
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
// Create OR
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
// Create XOR
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
// Create HALF_ADDER
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]), // Output bit
AND.eval(inputs[0], inputs[1]) // Carry bit
};
}
};
// Create FULL_ADDER
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
// Inputs: CarryIn, A, B
// Outputs: S, CarryOut
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0], // Output bit
OR.eval(haOutputs1[1], haOutputs2[1]) // Carry bit
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
// Inputs: A0, A1, A2..., B0, B1, B2...
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; // CarryIn
faInputs[1] = inputs[i]; // Ai
faInputs[2] = inputs[numBits + i]; // Bi
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0]; // Si
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1]; // CarryOut
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
// Convert input numbers into array of bits
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
}
|
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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
A burning cell turns into an empty cell
A tree will burn if at least one neighbor is burning
A tree ignites with probability f even if no neighbor is burning
An empty space fills with a tree with probability p
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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
function "+" (Left : Boolean; Right : Cell) return Boolean is
begin
return Left or else Right = Fire;
end "+";
function "+" (Left, Right : Cell) return Boolean is
begin
return Left = Fire or else Right = Fire;
end "+";
Above : array (S'Range (2)) of Cell := (others => Empty);
Left_Up, Up, Left : Cell;
begin
for Row in S'First (1) + 1..S'Last (1) - 1 loop
Left_Up := Empty;
Up := Empty;
Left := Empty;
for Column in S'First (2) + 1..S'Last (2) - 1 loop
Left_Up := Up;
Up := Above (Column);
Above (Column) := S (Row, Column);
case S (Row, Column) is
when Empty =>
if Random (Dice) < P then
S (Row, Column) := Tree;
end if;
when Tree =>
if Left_Up + Up + Above (Column + 1) +
Left + S (Row, Column) + S (Row, Column + 1) +
S (Row + 1, Column - 1) + S (Row + 1, Column) + S (Row + 1, Column + 1)
or else Random (Dice) < F then
S (Row, Column) := Fire;
end if;
when Fire =>
S (Row, Column) := Empty;
end case;
Left := Above (Column);
end loop;
end loop;
end Step;
procedure Put (S : Board) is
begin
for Row in S'First (1) + 1..S'Last (1) - 1 loop
for Column in S'First (2) + 1..S'Last (2) - 1 loop
case S (Row, Column) is
when Empty => Put (' ');
when Tree => Put ('Y');
when Fire => Put ('#');
end case;
end loop;
New_Line;
end loop;
end Put;
Dice : Generator;
Forest : Board := (1..10 => (1..40 => Empty));
begin
Reset (Dice);
for I in 1..10 loop
Step (Forest, 0.3, 0.1, Dice);
Put_Line ("-------------" & Integer'Image (I) & " -------------");
Put (Forest);
end loop;
end Forest_Fire;
|
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 formatted result list
print ('[')
var comma = ""
foreach item newl {
print (comma + item)
comma = ", "
}
println("]")
|
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 becomes 0, and any 0 becomes 1 for that whole row or column.
Task
Create a program to score for the Flipping bits game.
The game should create an original random target configuration and a starting configuration.
Ensure that the starting position is never the target position.
The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a 3×3 array of bits.
|
#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 new Ada.Numerics.Discrete_Random(Boolean);
Gen: Boolean_Rand.Generator;
type Matrix is array
(Letter range 'a' .. Last_Col, Positive range 1 .. Last_Row) of Boolean;
function Rand_Mat return Matrix is
M: Matrix;
begin
for I in M'Range(1) loop
for J in M'Range(2) loop
M(I,J) := Boolean_Rand.Random(Gen);
end loop;
end loop;
return M;
end Rand_Mat;
function Rand_Mat(Start: Matrix) return Matrix is
M: Matrix := Start;
begin
for I in M'Range(1) loop
if Boolean_Rand.Random(Gen) then
for J in M'Range(2) loop
M(I,J) := not M(I, J);
end loop;
end if;
end loop;
for I in M'Range(2) loop
if Boolean_Rand.Random(Gen) then
for J in M'Range(1) loop
M(J,I) := not M(J, I);
end loop;
end if;
end loop;
return M;
end Rand_Mat;
procedure Print(Message: String; Mat: Matrix) is
package NIO is new Ada.Text_IO.Integer_IO(Natural);
begin
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line(Message);
Ada.Text_IO.Put(" ");
for Ch in Matrix'Range(1) loop
Ada.Text_IO.Put(" " & Ch);
end loop;
Ada.Text_IO.New_Line;
for I in Matrix'Range(2) loop
NIO.Put(I, Width => 3);
for Ch in Matrix'Range(1) loop
Ada.Text_IO.Put(if Mat(Ch, I) then " 1" else " 0");
end loop;
Ada.Text_IO.New_Line;
end loop;
end Print;
Current, Target: Matrix;
Moves: Natural := 0;
begin
-- choose random Target and start ("Current") matrices
Boolean_Rand.Reset(Gen);
Target := Rand_Mat;
loop
Current := Rand_Mat(Target);
exit when Current /= Target;
end loop;
Print("Target:", Target);
-- print and modify Current matrix, until it is identical to Target
while Current /= Target loop
Moves := Moves + 1;
Print("Current move #" & Natural'Image(Moves), Current);
Ada.Text_IO.Put_Line("Flip row 1 .." & Positive'Image(Last_Row) &
" or column 'a' .. '" & Last_Col & "'");
declare
S: String := Ada.Text_IO.Get_Line;
function Let(S: String) return Character is (S(S'First));
function Val(Str: String) return Positive is (Positive'Value(Str));
begin
if Let(S) in 'a' .. Last_Col then
for I in Current'Range(2) loop
Current(Let(S), I) := not Current(Let(S), I);
end loop;
else
for I in Current'Range(1) loop
Current(I, Val(S)) := not Current(I, Val(S));
end loop;
end if;
end;
end loop;
-- summarize the outcome
Ada.Text_IO.Put_Line("Done after" & Natural'Image(Moves) & " Moves.");
end Flip_Bits;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.