task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#BBC_BASIC
|
BBC BASIC
|
GOSUB subroutine
(loop)
PRINT "Infinite loop"
GOTO loop
END
(subroutine)
PRINT "In subroutine"
WAIT 100
RETURN
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Bracmat
|
Bracmat
|
( LOOP
= out$"Hi again!"
& !LOOP
)
& out$Hi!
& !LOOP
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the 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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
magic[num_] := Capitalize[ StringRiffle[ Partition[
FixedPointList[IntegerName[StringLength[#], "Cardinal"] &, IntegerName[num, "Cardinal"]],
2, 1] /. {n_, n_} :> {n, "magic"}, ", ", " is "] <> "."]
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the 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
|
#Nim
|
Nim
|
import strutils
const
Small = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
Tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
Illions = ["", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"]
#---------------------------------------------------------------------------------------------------
func say(n: int64): string =
var n = n
if n < 0:
result = "negative "
n = -n
if n < 20:
result &= Small[n]
elif n < 100:
result &= Tens[n div 10]
let m = n mod 10
if m != 0: result &= '-' & Small[m]
elif n < 1000:
result &= Small[n div 100] & " hundred"
let m = n mod 100
if m != 0: result &= ' ' & m.say()
else:
# Work from right to left.
var sx = ""
var i = 0
while n > 0:
let m = n mod 1000
n = n div 1000
if m != 0:
var ix = m.say() & Illions[i]
if sx.len > 0: ix &= " " & sx
sx = ix
inc i
result &= sx
#---------------------------------------------------------------------------------------------------
func fourIsMagic(n: int64): string =
var n = n
var s = n.say().capitalizeAscii()
result = s
while n != 4:
n = s.len.int64
s = n.say()
result &= " is " & s & ", " & s
result &= " is magic."
#———————————————————————————————————————————————————————————————————————————————————————————————————
for n in [int64 0, 4, 6, 11, 13, 75, 100, 337, -164, int64.high]:
echo fourIsMagic(n)
|
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.
|
#360_Assembly
|
360 Assembly
|
* Floyd's triangle 21/06/2018
FLOYDTRI PROLOG
L R5,NN nn
BCTR R5,0 -1
M R4,NN nn*(nn-1)
SRA R5,1 /2
A R5,NN m=(nn*(nn-1))/2+nn; max_value
CVD R5,XDEC binary to packed decimal (PL8)
EDMK ZN,XDEC+4 packed dec (PL4) to char (CL8)
S R1,=A(ZN) r1=number of spaces
L R9,=A(L'ZN+1) length(zn08)+1
SR R9,R1 s=length(m)+1
SR R8,R8 k=0
LA R6,1 i=1
DO WHILE=(C,R6,LE,NN) do i=1 to nn
LA R10,PG pgi=0
LA R7,1 j=1
DO WHILE=(CR,R7,LE,R6) do j=1 to i
LA R8,1(R8) k=k+1
XDECO R8,XDEC k
LA R11,XDEC+12 +12
SR R11,R9 -s
LR R2,R9 s
BCTR R2,0 -1
EX R2,MVCX mvc @PG+pgi,@XDEC+12-s,LEN=s
AR R10,R9 pgi+=s
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
EPILOG
MVCX MVC 0(0,R10),0(R11) mvc PG,XDEC
NN DC F'14' number of rows
PG DC CL80' ' buffer
XDEC DS CL12 temp
ZN DC X'4020202020202020' mask CL8 7num
YREGS
END FLOYDTRI
|
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.
|
#Action.21
|
Action!
|
PROC Triangle(BYTE level)
INT v,i
BYTE x,y
BYTE ARRAY widths(20)
CHAR ARRAY tmp(5)
v=1
FOR y=1 TO level-1
DO
v==+y
OD
FOR x=0 TO level-1
DO
StrI(v+x,tmp)
widths(x)=tmp(0)
OD
v=1
FOR y=1 TO level
DO
FOR x=0 TO y-1
DO
StrI(v,tmp)
FOR i=tmp(0) TO widths(x)-1
DO
Put(32)
OD
Print(tmp)
IF x<y-1 THEN
Put(32)
ELSE
PutE()
FI
v==+1
OD
OD
RETURN
PROC Main()
BYTE LMARGIN=$52,oldLMARGIN
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
Triangle(5)
PutE()
Triangle(13)
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN
|
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.
|
#J
|
J
|
_80 ]\ fread 'flr-infile.dat' NB. reads the file into a n by 80 array
_80 |.\ fread 'flr-infile.dat' NB. as above but reverses each 80 byte chunk
'flr-outfile.dat' fwrite~ , _80 |.\ fread 'flr-infile.dat' NB. as above but writes result to file (720 bytes)
processFixLenFile=: fwrite~ [: , _80 |.\ fread NB. represent operation as a verb/function
|
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.
|
#jq
|
jq
|
jq -Rrs -f program.jq infile.dat
|
http://rosettacode.org/wiki/Fixed_length_records
|
Fixed length records
|
Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, 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.
|
#Julia
|
Julia
|
function processfixedlengthrecords(infname, blocksize, outfname)
inf = open(infname)
outf = open(outfname, "w")
filedata = [ read(inf, blocksize) for _ in 1:10 ]
for line in filedata
s = join([Char(c) for c in line], "")
@assert(length(s) == blocksize)
write(outf, s)
end
end
processfixedlengthrecords("infile.dat", 80, "outfile.dat")
|
http://rosettacode.org/wiki/Fixed_length_records
|
Fixed length records
|
Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, 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.
|
#Lua
|
Lua
|
-- prep: convert given sample text to fixed length "infile.dat"
local sample = [[
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 RT MARGIN]]
local txtfile = io.open("sample.txt", "w")
txtfile:write(sample)
txtfile:close()
os.execute("dd if=sample.txt of=infile.dat cbs=80 conv=block > /dev/null 2>&1")
-- task: convert fixed length "infile.dat" to fixed length "outfile.dat" (reversed lines)
local infile = io.open("infile.dat", "rb")
local outfile = io.open("outfile.dat", "wb")
while true do
local line = infile:read(80)
if not line then break end
outfile:write(string.reverse(line))
end
infile:close()
outfile:close()
-- output:
os.execute("dd if=outfile.dat cbs=80 conv=unblock")
|
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)
|
#Common_Lisp
|
Common Lisp
|
#!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#
(progn ;;init forms
(ros:ensure-asdf)
#+quicklisp(ql:quickload '() :silent t)
)
(defpackage :ros.script.floyd-warshall.3861181636
(:use :cl))
(in-package :ros.script.floyd-warshall.3861181636)
;;;
;;; Floyd-Warshall algorithm.
;;;
;;; See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
;;;
;;; Translated from the Scheme. Small improvements (or what might be
;;; considered improvements), and some type specialization, have been
;;; added.
;;;
;;;-------------------------------------------------------------------
;;;
;;; A square array will be represented by an ordinary Common Lisp
;;; array, but accessed through our own functions (which look similar
;;; to, although not identical to, the corresponding Scheme
;;; functions).
;;;
;;; Square arrays are indexed *starting at one*.
;;;
(defun make-arr (n &key (element-type t) initial-element)
(make-array (list n n) :element-type element-type
:initial-element initial-element))
(defun arr-set (arr i j x)
(setf (aref arr (- i 1) (- j 1)) x))
(defun arr-ref (arr i j)
(aref arr (- i 1) (- j 1)))
;;;-------------------------------------------------------------------
;;;
;;; Floyd-Warshall.
;;;
;;; Input is a list of length-3 lists representing edges; each entry
;;; is:
;;;
;;; (start-vertex edge-weight end-vertex)
;;;
;;; where vertex identifiers are integers from 1 .. n.
;;;
;;; A difference from the Scheme implementation is that here we do not
;;; assume the floating point supports "infinities". In the Scheme we
;;; did, because in R7RS small there is support for such infinities
;;; (although the standard does not *require* them). Also because
;;; alternatives were not yet apparent to this author. :)
;;;
(defvar *floatpt* 'single-float)
(defconstant nil-vertex 0)
(defun floyd-warshall (edges)
(let* ((n
;; Set n to the maximum vertex number. By design, n also
;; equals the number of vertices.
(max (apply #'max (mapcar #'car edges))
(apply #'max (mapcar #'caddr edges))))
(distance
;; The distances are initialized to a purely arbitrary
;; value. An entry in the "distance" array is meaningful
;; *only* if the corresponding entry in "next-vertex" is
;; not the nil-vertex.
(make-arr n :element-type *floatpt*
:initial-element (coerce 12345 *floatpt*)))
(next-vertex
;; Unless later set otherwise, an entry in "next-vertex"
;; will be the nil-vertex.
(make-arr n :element-type 'fixnum
:initial-element nil-vertex)))
(defun dist (p q) (arr-ref distance p q))
(defun next (p q) (arr-ref next-vertex p q))
(defun set-dist (p q x) (arr-set distance p q x))
(defun set-next (p q x) (arr-set next-vertex p q x))
(defun nilnext (p q) (= (next p q) nil-vertex))
;; Initialize "distance" and "next-vertex".
(loop for edge in edges
do (let ((u (car edge))
(weight (cadr edge))
(v (caddr edge)))
(set-dist u v weight)
(set-next u v v)))
(loop for v from 1 to n
do (progn
;; The distance from a vertex to itself = 0.0.
(set-dist v v (coerce 0 *floatpt*))
(set-next v v v)))
;; Perform the algorithm.
(loop
for k from 1 to n
do (loop
for i from 1 to n
do (loop
for j from 1 to n
do (and (not (nilnext i k))
(not (nilnext k j))
(let* ((dist-ikj (+ (dist i k) (dist k j))))
(when (or (nilnext i j)
(< dist-ikj (dist i j)))
(set-dist i j dist-ikj)
(set-next i j (next i k))))))))
;; Return the results.
(values n distance next-vertex)))
;;;-------------------------------------------------------------------
;;;
;;; Path reconstruction from the "next-vertex" array.
;;;
;;; The return value is a list of vertices.
;;;
(defun find-path (next-vertex u v)
(if (= (arr-ref next-vertex u v) nil-vertex)
(list)
(cons u (let ((i u))
(loop while (/= i v)
do (setf i (arr-ref next-vertex i v))
collect i)))))
;;;-------------------------------------------------------------------
(defun directed-vertex-list-to-string (lst)
(if (not lst)
""
(let ((s (write-to-string (car lst))))
(loop for u in (cdr lst)
do (setf s (concatenate 'string s " -> "
(write-to-string u))))
s)))
;;;-------------------------------------------------------------------
(defun main (&rest argv)
(declare (ignorable argv))
(let ((example-graph
(mapcar (lambda (x) (list (coerce (car x) 'fixnum)
(coerce (cadr x) *floatpt*)
(coerce (caddr x) 'fixnum)))
'((1 -2 3)
(3 2 4)
(4 -1 2)
(2 4 1)
(2 3 3)))))
(multiple-value-bind (n distance next-vertex)
(floyd-warshall example-graph)
(princ " pair distance path")
(terpri)
(princ "-------------------------------------")
(terpri)
(loop
for u from 1 to n
do (loop
for v from 1 to n
do (unless (= u v)
(format
t " ~A ~7@A ~A~%"
(directed-vertex-list-to-string (list u v))
(if (= (arr-ref next-vertex u v) nil-vertex)
" no path"
(write-to-string (arr-ref distance u v)))
(directed-vertex-list-to-string
(find-path next-vertex u v)))))))))
;;;-------------------------------------------------------------------
;;; vim: set ft=lisp lisp:
|
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.2FSQL
|
PL/SQL
|
FUNCTION multiply(p_arg1 NUMBER, p_arg2 NUMBER) RETURN NUMBER
IS
v_product NUMBER;
BEGIN
v_product := p_arg1 * p_arg2;
RETURN v_product;
END;
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer 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.)
|
#Haskell
|
Haskell
|
forwardDifference :: Num a => [a] -> [a]
forwardDifference = tail >>= zipWith (-)
nthForwardDifference :: Num a => [a] -> Int -> [a]
nthForwardDifference = (!!) . iterate forwardDifference
main :: IO ()
main =
mapM_ print $
take 10 (iterate forwardDifference [90, 47, 58, 29, 22, 32, 55, 5, 55, 73])
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Wisp
|
Wisp
|
import : scheme base
scheme write
display "Hello world!"
newline
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
StringTake["000000" <> ToString[7.125], -9]
00007.125
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
>> disp(sprintf('%09.3f',7.125))
00007.125
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands 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).
|
#JavaScript
|
JavaScript
|
function acceptedBinFormat(bin) {
if (bin == 1 || bin === 0 || bin === '0')
return true;
else
return bin;
}
function arePseudoBin() {
var args = [].slice.call(arguments), len = args.length;
while(len--)
if (acceptedBinFormat(args[len]) !== true)
throw new Error('argument must be 0, \'0\', 1, or \'1\', argument ' + len + ' was ' + args[len]);
return true;
}
|
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.
|
#ALGOL_68
|
ALGOL 68
|
LONG REAL tree prob = 0.55, # original tree probability #
f prob = 0.01, # new combustion probability #
p prob = 0.01; # tree creation probability #
MODE CELL = CHAR; CELL empty=" ", tree="T", burning="#";
MODE WORLD = [6, 65]CELL;
PROC has burning neighbours = (WORLD world, INT r, c)BOOL:(
FOR row shift FROM -1 TO 1 DO
FOR col shift FROM -1 TO 1 DO
INT rs = r + row shift, cs = c + col shift;
IF rs >= LWB world AND rs <= UPB world AND
cs >= 2 LWB world AND cs <= 2 UPB world THEN
IF world[rs, cs] = burning THEN true exit FI
FI
OD
OD;
FALSE EXIT
true exit: TRUE
);
PROC next state = (REF WORLD world, REF WORLD next world)VOID:(
FOR r FROM LWB world TO UPB world DO
REF[]CELL row = world[r, ];
FOR c FROM LWB row TO UPB row DO
REF CELL elem = row[c];
next world[r, c] :=
IF elem = empty THEN
IF random<p prob THEN tree ELSE empty FI
ELIF elem = tree THEN
IF has burning neighbours(world, r, c) THEN
burning
ELSE
IF random<f prob THEN burning ELSE tree FI
FI
ELIF elem = burning THEN
empty
FI
OD
OD;
world := next world
);
main:(
WORLD world; # create world #
FOR r FROM LWB world TO UPB world DO
REF []CELL row = world[r, ];
FOR i FROM LWB row TO UPB row DO
REF CELL el = row[i];
el := IF random < tree prob THEN tree ELSE empty FI
OD
OD;
WORLD next world;
FOR i FROM 0 TO 4 DO
next state(world, next world);
printf(($n(2 UPB world)(a)l$, world)); # show world #
printf(($gl$, 2 UPB world * "-"))
OD
)
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Aime
|
Aime
|
void
show_list(list l)
{
integer i, k;
o_text("[");
i = 0;
while (i < ~l) {
o_text(i ? ", " : "");
if (l_j_integer(k, l, i)) {
o_integer(k);
} else {
show_list(l[i]);
}
i += 1;
}
o_text("]");
}
list
flatten(list c, object o)
{
if (__id(o) == INTEGER_ID) {
c.append(o);
} else {
l_ucall(o, flatten, 1, c);
}
c;
}
integer
main(void)
{
list l;
l = list(list(1), 2, list(list(3, 4), 5),
list(list(list())), list(list(list(6))), 7, 8, list());
show_list(l);
o_byte('\n');
show_list(flatten(list(), l));
o_byte('\n');
return 0;
}
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 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.
|
#APL
|
APL
|
#!/usr/local/bin/apl -s --
∇r←b FlipRow ix ⍝ Flip a row
r←b
r[ix;]←~r[ix;]
∇
∇r←b FlipCol ix ⍝ Flip a column
r←b
r[;ix]←~r[;ix]
∇
∇r←RandFlip b;ix ⍝ Flip a random row or column
ix←?↑⍴b
→(2|?2)/col
r←b FlipRow ix ⋄ →0
col: r←b FlipCol ix
∇
∇s←ttl ShowBoard b;d ⍝ Add row, column indices and title to board
s←'-'⍪⍕(' ',⎕UCS 48+d),(⎕UCS 64+d←⍳↑⍴b)⍪b
s←((2⊃⍴s)↑ttl)⍪s
∇
∇b←MkBoard n ⍝ Generate random board
b←(?(n,n)⍴2)-1
∇
∇Game;n;board;goal;moves;swaps;in;tgt
⍝⍝ Initialize
⎕RL←(2*32)|×/⎕TS ⍝ random seed from time
→(5≠⍴⎕ARG)/usage ⍝ check argument
→(~'0123456789'∧.∊⍨n←5⊃⎕ARG)/usage
→((3>n)∨8<n←⍎n)/usage
board←goal←MkBoard n ⍝ Make a random board of the right size
swaps←4+?16 ⍝ 5 to 20 swaps
board←(RandFlip⍣swaps)board
moves←0
⎕←'*** Flip the bits! ***'
⎕←'----------------------'
⍝⍝ Print game state
state: ⎕←''
⎕←'Swaps:',moves,' Goal:',swaps
⎕←''
('Board'ShowBoard board),' ',' ',' ',' ','Goal'ShowBoard goal
⍝⍝ Handle move
⍞←'Press line or column to flip, or Q to quit: '
read: in←32⊤∨1⎕FIO[41]1
→(in=⎕UCS'q')/0
→((97≤in)∧(tgt←in-96)≤n)/col
→((49≤in)∧(tgt←in-48)≤n)/row
→read
col: ⍞←⎕UCS in ⋄ board←board FlipCol tgt ⋄ →check
row: ⍞←⎕UCS in ⋄ board←board FlipRow tgt
⍝⍝ Check if player won
check: →(board≡goal)/win
moves←moves+1
→state
win: ⎕←'You win!'
→0
usage: ⎕←'Usage:',⎕ARG[4],'[3..8]; number is board size.'
∇
Game
)OFF
|
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.
|
#AutoHotkey
|
AutoHotkey
|
size := 3 ; max 26
Gui, Add, Button, , O
Loop, %size%
{
x := chr(A_Index+64)
If x = A
Loop, %size%
Gui, Add, Button, y+4 gFlip, % A_Index
Gui, Add, Button, ym gFlip, % x
Loop, %size%
{
y := A_Index
Random, %x%%y%, 0, 1
Gui, Add, Edit, v%x%%y% ReadOnly, % %x%%y%
}
}
Gui, Add, Text, ym, Moves:`nTarget:
Loop, %size%
{
x := chr(A_Index+64)
Loop, %size%
{
y := A_Index
Gui, Add, Edit, % y=1 ? x="A" ? "xp+0 ym+30" : "x+14 ym+30" : "" . "ReadOnly vt" x y, % t%x%%y% := %x%%y%
}
}Gui, Add, Text, xp-18 ym w30 Right vMoves, % Moves:=1
; randomize
While (i < size)
{
Random, z, 1, %size%
Random, x, 0, 1
z := x ? chr(z+64) : z
Solution .= z ; to cheat
If Flip(z, size)
i := 0 ; ensure we are not at the solution
Else
i++ ; count
}
Gui, Show, NA
Return
Flip(z, size) {
Loop, %size%
{
If z is alpha
GuiControl, , %z%%A_Index%, % %z%%A_Index% := !%z%%A_Index%
Else
{
AIndex := chr(A_Index+64)
GuiControl, , %AIndex%%z%, % %AIndex%%z% := !%AIndex%%z%
}
}
Loop, %size%
{
x := chr(A_Index+64)
Loop, %size%
{
y := A_Index
If (%x%%y% != t%x%%y%)
Return 0
}
}
Return 1
}
Flip:
GuiControl, , Moves, % Moves++
If Flip(A_GuiControl, size)
{
Msgbox Success in %Moves% moves!
Reload
}
Return
ButtonO:
Reload
Return
GuiEscape:
GuiClose:
ExitApp
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
|
#C
|
C
|
int main()
{
int i,j;
for (j=1; j<1000; j++) {
for (i=0; i<j, i++) {
if (exit_early())
goto out;
/* etc. */
}
}
out:
return 0;
}
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#C.23
|
C#
|
int GetNumber() {
return 5;
}
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the 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
|
#Perl
|
Perl
|
use Lingua::EN::Numbers qw(num2en);
sub cardinal {
my($n) = @_;
(my $en = num2en($n)) =~ s/\ and|,//g;
$en;
}
sub magic {
my($int) = @_;
my $str;
while () {
$str .= cardinal($int) . " is ";
if ($int == 4) {
$str .= "magic.\n";
last
} else {
$int = length cardinal($int);
$str .= cardinal($int) . ", ";
}
}
ucfirst $str;
}
print magic($_) for 0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209;
|
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.
|
#Ada
|
Ada
|
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line;
procedure Floyd_Triangle is
rows : constant Natural := Natural'Value(Ada.Command_Line.Argument(1));
begin
for r in 1..rows loop
for i in 1..r loop
Ada.Integer_Text_IO.put (r*(r-1)/2+i, Width=> Natural'Image(rows*(rows-1)/2+i)'Length);
end loop;
Ada.Text_IO.New_Line;
end loop;
end Floyd_Triangle;
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module FixedFile {
Read fixed$
OldLocale=Locale
\\ chr$(string_argument$)
\\ use Locale to convert from Ansi to Utf-16LE
\\ Read Ansi form files also use Locale
Locale 1032
Try ok {
\\ Make the file first
Const Center=2
Font "Courier New"
Bold 0
Italic 0
Def long m, z=1, f
Def text2read$,test3write$
Form 100, 50 ' 100 by 60 characters
Document txt$={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
}
\\ use Help Open in M2000 console for details
\\ Method one
Report Center, "Make file"
\\ for WIDE Random \\ for Utf-16
Open fixed$ for Random Exclusive as #f len=80
m=Paragraph(txt$, 0)
z=1
If forward(txt$, m) then
while m, z<10
text2write$=Paragraph$(txt$,(m))
Print format$("Len:{0}, Data: {1}",Len(text2write$),text2write$)
Put #f, text2write$ , z
\\ record number from 1
\\ if number is total records plus one
\\ we append a record
z++
End while
End If
Print "Press any key"
Push Key$ : Drop
Form 80, 40
Report Center, "Method1"
For z=1 to 9
Get #f, text2read$, z
text2read$=StrRev$(text2read$)
Put #f, text2read$, z
Print text2read$
Next z
Close #f
Report Center, "Method2"
\\ Method2
\\ Buffer Clear Line80 ... \\ to clear memory
\\ here we write all bytes so not needed
Buffer Line80 as byte*80
m=filelen(fixed$)
If m mod 80=0 Then
m=1
\\ now Get/Put read write at byte position
\\ we have to use seek to move to byte position
\\ This way used for Binary files
Open fixed$ for Input as #f1
Open fixed$ for Append as #f2
while not eof(#f1)
seek #f1, m
Rem Print seek(#f)
Get #f1, Line80
Return line80,0:=Str$(StrRev$(Chr$(Eval$(line80,0,80))))
seek #f2, m
Put #f2, Line80
seek #f1, m
Get #f1, Line80
Print Chr$(Eval$(line80,0,80))
m+=80
End While
Close #f1
Close #f2
End if
}
\\ use Close with no parameters for close all files if something happen
If error then Close: Print Error$
Locale OldLocale
}
FixedFile "fixed.random"
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
FixedRecordReverse[inFile_File, outFile_File, length_ : 80] :=
Module[{inStream, outStream, line, byte},
WithCleanup[
inStream = OpenRead[inFile, BinaryFormat -> True];
outStream = OpenWrite[outFile, BinaryFormat -> True];
,
While[True,
line = {};
Do[
byte = BinaryRead[inStream, "Byte"];
AppendTo[line, byte]
,
length
];
If[byte === EndOfFile, Break[]];
line = Reverse[line];
BinaryWrite[outStream, line]
]
,
Close[outStream];
Close[inStream];
];
(* Verify the result *)
RunProcess[{"dd", "if=" <> outFile[[1]], "cbs=" <> ToString[length], "conv=unblock"}, "StandardOutput"]
];
|
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.
|
#Neko
|
Neko
|
/**
fixed length records, in Neko
*/
var LRECL = 80
var reverse = function(s) {
var len = $ssize(s)
if len < 2 return s
var reverse = $smake(len)
var pos = 0
while len > 0 $sset(reverse, pos ++= 1, $sget(s, len -= 1))
return reverse
}
var file_open = $loader.loadprim("std@file_open", 2)
var file_read = $loader.loadprim("std@file_read", 4)
var file_write = $loader.loadprim("std@file_write", 4)
var file_close = $loader.loadprim("std@file_close", 1)
var input = file_open("infile.dat", "r")
var output = file_open("outfile.dat", "w")
var len
var pos = 0
var record = $smake(LRECL)
while true {
try {
len = file_read(input, record, pos, LRECL)
if len != LRECL $throw("Invalid read")
len = file_write(output, reverse(record), pos, LRECL)
if len != LRECL $throw("Invalid write")
} catch a break;
}
file_close(input)
file_close(output)
|
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)
|
#D
|
D
|
import std.stdio;
void main() {
int[][] weights = [
[1, 3, -2],
[2, 1, 4],
[2, 3, 3],
[3, 4, 2],
[4, 2, -1]
];
int numVertices = 4;
floydWarshall(weights, numVertices);
}
void floydWarshall(int[][] weights, int numVertices) {
import std.array;
real[][] dist = uninitializedArray!(real[][])(numVertices, numVertices);
foreach(dim; dist) {
dim[] = real.infinity;
}
foreach (w; weights) {
dist[w[0]-1][w[1]-1] = w[2];
}
int[][] next = uninitializedArray!(int[][])(numVertices, numVertices);
for (int i=0; i<next.length; i++) {
for (int j=0; j<next.length; j++) {
if (i != j) {
next[i][j] = j+1;
}
}
}
for (int k=0; k<numVertices; k++) {
for (int i=0; i<numVertices; i++) {
for (int j=0; j<numVertices; 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];
}
}
}
}
printResult(dist, next);
}
void printResult(real[][] dist, int[][] next) {
import std.conv;
import std.format;
writeln("pair dist path");
for (int i=0; i<next.length; i++) {
for (int j=0; j<next.length; j++) {
if (i!=j) {
int u = i+1;
int v = j+1;
string path = format("%d -> %d %2d %s", u, v, cast(int) dist[i][j], u);
do {
u = next[u-1][v-1];
path ~= text(" -> ", u);
} while (u != v);
writeln(path);
}
}
}
}
|
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
|
#Plain_English
|
Plain English
|
To multiply a number with another number:
Multiply the number by the other number.
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Pop11
|
Pop11
|
define multiply(a, b);
a * b
enddefine;
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer 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.)
|
#HicEst
|
HicEst
|
REAL :: n=10, list(n)
list = ( 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 )
WRITE(Format='i1, (i6)') 0, list
DO i = 1, n-1
ALIAS(list,1, diff,n-i) ! rename list(1 ... n-i) with diff
diff = list($+1) - diff ! $ is the running left hand array index
WRITE(Format='i1, (i6)') i, diff
ENDDO
END
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Wolfram_Language
|
Wolfram Language
|
Print["Hello world!"]
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Mercury
|
Mercury
|
:- module formatted_numeric_output.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string.
main(!IO) :-
io.format("%09.3f\n", [f(7.125)], !IO).
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#min
|
min
|
(quote cons "" join) :str-append
(pick length - repeat swap str-append) :left-pad
7.125 string "0" 9 left-pad puts!
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands 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).
|
#jq
|
jq
|
# Start with the 'not' and 'and' building blocks.
# These allow us to construct 'nand', 'or', and 'xor',
# and so on.
def bit_not: if . == 1 then 0 else 1 end;
def bit_and(a; b): if a == 1 and b == 1 then 1 else 0 end;
def bit_nand(a; b): bit_and(a; b) | bit_not;
def bit_or(a; b): bit_nand(bit_nand(a;a); bit_nand(b;b));
def bit_xor(a; b):
bit_nand(bit_nand(bit_nand(a;b); a);
bit_nand(bit_nand(a;b); b));
def halfAdder(a; b):
{ "carry": bit_and(a; b), "sum": bit_xor(a; b) };
def fullAdder(a; b; c):
halfAdder(a; b) as $h0
| halfAdder($h0.sum; c) as $h1
| {"carry": bit_or($h0.carry; $h1.carry), "sum": $h1.sum };
# a and b should be strings of 0s and 1s, of length no greater than 4
def fourBitAdder(a; b):
# pad on the left with 0s, and convert the string
# representation ("101") to an array of integers ([1,0,1]).
def pad: (4-length) * "0" + . | explode | map(. - 48);
(a|pad) as $inA | (b|pad) as $inB
| [][3] = null # an array for storing the four results
| halfAdder($inA[3]; $inB[3]) as $pass
| .[3] = $pass.sum # store the lsb
| fullAdder($inA[2]; $inB[2]; $pass.carry) as $pass
| .[2] = $pass.sum
| fullAdder($inA[1]; $inB[1]; $pass.carry) as $pass
| .[1] = $pass.sum
| fullAdder($inA[0]; $inB[0]; $pass.carry) as $pass
| .[0] = $pass.sum
| map(tostring) | join("") ;
|
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.
|
#AutoHotkey
|
AutoHotkey
|
; The array Frame1%x%_%y% holds the current frame. frame2%x%_%y%
; is then calculated from this, and printed. frame2 is then copied to frame1.
; Two arrays are necessary so that each cell advances at the same time
; T=Tree, #=Fire, O=Empty cell
; Size holds the width and height of the map and is used as the # of iterations in loops
; This will save the map as forest_fire.txt in its working directory
; ======================================================================================
Size := 10
Generation := 0
Tree := "T"
Fire := "#"
Cell := "O"
; --Define probabilities--
New_Tree := 5
; 20 percent chance (1 in 5). A random number will be generated from 1 to New_tree. If this number is 1,
; A tree will be created in the current cell
Spontaneous := 10
; 10 percent chance (1 in 10). A random number will be generated from 1 to Spontaneous. If this number is 1,
; and the current cell contains a tree, the tree in the current cell will become fire.
GoSub, Generate
; ----------------------Main Loop------------------------------
loop
{
Generation++
GoSub, Calculate
GoSub, Copy
GoSub, Display
msgbox, 4, Forest Fire, At Generation %generation%. Continue?
IfMsgbox, No
ExitApp
}
return
; -------------------------------------------------------------
Generate: ; Randomly initializes the map.
loop % size ; % forces expression mode.
{
x := A_Index
Loop % size
{
Y := A_Index
Random, IsTree, 1, 2 ; -- Roughly half of the spaces will contain trees
If ( IsTree = 1 )
Frame1%x%_%y% := Tree
Else
Frame1%x%_%y% := Cell
}
}
return
Calculate:
Loop % size
{
x := A_Index
Loop % size
{
Y := A_Index
If ( Frame1%x%_%y% = Cell )
{
Random, tmp, 1, New_Tree
If ( tmp = 1 )
Frame2%x%_%y% := tree
Else
Frame2%x%_%y% := Cell
}
Else If ( Frame1%x%_%y% = Tree )
{
BoolCatch := PredictFire(x,y)
If (BoolCatch)
Frame2%x%_%y% := Fire
Else
Frame2%x%_%y% := Tree
}
Else If ( Frame1%x%_%y% = Fire )
Frame2%x%_%y% := Cell
Else
{
contents := Frame1%x%_%y%
Msgbox Error! Cell %x% , %y% contains %contents% ; This has never happened
ExitApp
}
}
}
return
Copy:
Loop % size
{
x := A_Index
Loop % size
{
y := A_Index
frame1%x%_%y% := Frame2%x%_%y%
}
}
return
Display:
ToPrint := ""
ToPrint .= "=====Generation " . Generation . "=====`n"
Loop % size
{
x := A_Index
Loop % size
{
y := A_Index
ToPrint .= Frame1%x%_%y%
}
ToPrint .= "`n"
}
FileAppend, %ToPrint%, Forest_Fire.txt
Return
PredictFire(p_x,p_y){
Global ; allows access to all frame1*_* variables (the pseudo-array)
A := p_x-1
B := p_y-1
C := p_x+1
D := p_y+1
If ( Frame1%A%_%p_Y% = fire )
return 1
If ( Frame1%p_X%_%B% = fire )
return 1
If ( Frame1%C%_%p_Y% = fire )
return 1
If ( Frame1%p_X%_%D% = fire )
return 1
If ( Frame1%A%_%B% = Fire )
return 1
If ( Frame1%A%_%D% = fire )
return 1
If ( Frame1%C%_%B% = fire )
return 1
If ( Frame1%C%_%D% = Fire )
return 1
Random, tmp, 1, spontaneous
if ( tmp = 1 )
return 1
return 0
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#ALGOL_68
|
ALGOL 68
|
main:(
[][][]INT list = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ());
print((list, new line))
)
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 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.
|
#BASIC
|
BASIC
|
10 DEFINT A-Z
20 PRINT "*** FLIP THE BITS ***"
30 INPUT "Board size";S
40 IF S<3 OR S>8 THEN PRINT "3 <= size <= 8": GOTO 30
50 RANDOMIZE
60 DIM B(S,S),G(S,S)
70 FOR X=1 TO S
80 FOR Y=1 TO S
90 B=INT(.5+RND(1))
100 B(X,Y)=B: G(X,Y)=B
110 NEXT Y,X
120 FOR A=0 TO 10+2*INT(10*RND(1))
130 R=INT(.5+RND(1))
140 N=1+INT(S*RND(1))
150 GOSUB 500
160 NEXT A: M=0
170 PRINT: M=M+1
180 PRINT " ==BOARD==";TAB(20);" ==GOAL=="
190 PRINT " ";: GOSUB 400
200 PRINT TAB(20);" ";: GOSUB 400
210 FOR N=1 TO S
220 FOR A=0 TO 1
230 PRINT TAB(A*20);CHR$(64+N);". ";
240 FOR C=1 TO S: IF A THEN B=G(C,N) ELSE B=B(C,N)
250 PRINT USING "# ";B;
260 NEXT C,A
270 PRINT
280 NEXT N
290 PRINT
300 LINE INPUT "Enter row or column: ";I$
310 IF LEN(I$)<>1 THEN 300 ELSE C=ASC(I$) OR 32
320 IF C<97 THEN N=C-48:R=0 ELSE N=C-96:R=1
330 IF N<1 OR N>S THEN 300 ELSE GOSUB 500
340 W=1=1
350 FOR X=1 TO S:FOR Y=1 TO S
360 W=W AND (B(X,Y)=G(X,Y))
370 NEXT Y,X
380 IF W THEN PRINT:PRINT "You win! Moves:";M:END
390 GOTO 170
400 FOR I=1 TO S: PRINT USING "# ";I;: NEXT I: RETURN
500 IF R THEN 510 ELSE 520
510 FOR I=1 TO S: B(I,N)=1-B(I,N): NEXT I: RETURN
520 FOR I=1 TO S: B(N,I)=1-B(N,I): NEXT I: 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
|
#C.2B.2B
|
C++
|
#include <iostream>
int main()
{
LOOP:
std::cout << "Hello, World!\n";
goto LOOP;
}
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#COBOL
|
COBOL
|
PROGRAM-ID. Go-To-Example.
PROCEDURE DIVISION.
Foo.
DISPLAY "Just a reminder: GO TOs are evil."
GO TO Foo
.
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the 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
|
#Phix
|
Phix
|
with javascript_semantics
--<adapted from demo\rosetta\number_names.exw, which alas outputs ",", "and", uses "minus" instead of "negative", etc...>
constant twenties = {"zero","one","two","three","four","five","six","seven","eight","nine","ten",
"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"},
decades = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}
function hundred(integer n)
if n<20 then
return twenties[mod(n,20)+1]
elsif mod(n,10)=0 then
return decades[mod(floor(n/10),10)-1]
end if
return decades[mod(floor(n/10),10)-1] & '-' & twenties[mod(n,10)+1]
end function
function thousand(integer n)
if n<100 then
return hundred(n)
elsif mod(n,100)=0 then
return twenties[mod(floor(n/100),20)+1]&" hundred"
end if
return twenties[mod(floor(n/100),20)+1] & " hundred " & hundred(mod(n,100))
end function
constant orders = {{power(10,12),"trillion"},
{power(10,9),"billion"},
{power(10,6),"million"},
{power(10,3),"thousand"}}
function triplet(integer n)
string res = ""
for i=1 to length(orders) do
{atom order, string name} = orders[i]
atom high = floor(n/order),
low = mod(n,order)
if high!=0 then
res &= thousand(high)&' '&name
end if
n = low
if low=0 then exit end if
if length(res) and high!=0 then
res &= " "
end if
end for
if n!=0 or res="" then
res &= thousand(floor(n))
end if
return res
end function
function spell(integer n)
string res = ""
if n<0 then
res = "negative "
n = -n
end if
res &= triplet(n)
return res
end function
--</adapted from number_names.exw>
function fourIsMagic(atom n)
string s = spell(n)
s[1] = upper(s[1])
string t = s
while n!=4 do
n = length(s)
s = spell(n)
t &= " is " & s & ", " & s
end while
t &= " is magic.\n"
return t
end function
constant tests = {-7, -1, 0, 1, 2, 3, 4, 23, 1e9, 20140, 100, 130, 151, 999999}
for i=1 to length(tests) do
puts(1,fourIsMagic(tests[i]))
end for
|
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.
|
#ALGOL_68
|
ALGOL 68
|
# procedure to print a Floyd's Triangle with n lines #
PROC floyds triangle = ( INT n )VOID:
BEGIN
# calculate the number of the highest number that will be printed #
# ( the sum of the integers 1, 2, ... n ) #
INT max number = ( n * ( n + 1 ) ) OVER 2;
# determine the widths required to print the numbers of the final row #
[ n ]INT widths;
INT number := max number + 1;
FOR col FROM n BY -1 TO 1 DO
widths[ col ] := - ( UPB whole( number -:= 1, 0 ) + 1 )
OD;
# print the triangle #
INT element := 0;
FOR row TO n DO
FOR col TO row DO
print( ( whole( element +:= 1, widths[ col ] ) ) )
OD;
print( ( newline ) )
OD
END; # floyds triangle #
main: (
floyds triangle( 5 );
print( ( newline ) );
floyds triangle( 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.
|
#Nim
|
Nim
|
import algorithm
proc reverse(infile, outfile: string) =
let input = infile.open(fmRead)
defer: input.close()
let output = outfile.open(fmWrite)
defer: output.close()
var buffer: array[80, byte]
while not input.endOfFile:
let countRead = input.readBytes(buffer, 0, 80)
if countRead < 80:
raise newException(IOError, "truncated data when reading")
buffer.reverse()
let countWrite = output.writeBytes(buffer, 0, 80)
if countWrite < 80:
raise newException(IOError, "truncated data when writing")
reverse("infile.dat", "outfile.dat")
|
http://rosettacode.org/wiki/Fixed_length_records
|
Fixed length records
|
Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, 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.
|
#Pascal
|
Pascal
|
program reverseFixedLines(input, output, stdErr);
const
lineLength = 80;
var
// in Pascal, `string[n]` is virtually an alias for `array[1..n] of char`
line: string[lineLength];
i: integer;
begin
while not eof() do
begin
for i := 1 to lineLength do
begin
read(line[i]);
end;
for i := lineLength downto 1 do
begin
write(line[i]);
end;
writeLn();
end;
end.
|
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)
|
#EchoLisp
|
EchoLisp
|
(lib 'matrix)
;; in : initialized dist and next matrices
;; out : dist and next matrices
;; O(n^3)
(define (floyd-with-path n dist next (d 0))
(for* ((k n) (i n) (j n))
#:break (< (array-ref dist j j) 0) => 'negative-cycle
(set! d (+ (array-ref dist i k) (array-ref dist k j)))
(when (< d (array-ref dist i j))
(array-set! dist i j d)
(array-set! next i j (array-ref next i k)))))
;; utilities
;; init random edges costs, matrix 66% filled
(define (init-edges n dist next)
(for* ((i n) (j n))
(array-set! dist i i 0)
(array-set! next i j null)
#:continue (= j i)
(array-set! dist i j Infinity)
#:continue (< (random) 0.3)
(array-set! dist i j (1+ (random 100)))
(array-set! next i j j)))
;; show path from u to v
(define (path u v)
(cond
((= u v) (list u))
((null? (array-ref next u v)) null)
(else (cons u (path (array-ref next u v) v)))))
(define( mdist u v) ;; show computed distance
(array-ref dist u v))
(define (task)
(init-edges n dist next)
(array-print dist) ;; show init distances
(floyd-with-path n dist next))
|
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
|
#PostScript
|
PostScript
|
3 4 mul
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer 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.)
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(A) # Compute all forward difference orders for argument list
every order := 1 to (*A-1) do showList(order, fdiff(A, order))
end
procedure fdiff(A, order)
every 1 to order do {
every put(B := [], A[i := 2 to *A] - A[i-1])
A := B
}
return A
end
procedure showList(order, L)
writes(right(order,3),": ")
every writes(!L," ")
write()
end
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Wren
|
Wren
|
System.print("Hello world!")
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Modula-3
|
Modula-3
|
IO.Put(Fmt.Pad("7.125\n", length := 10, padChar := '0'));
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Nanoquery
|
Nanoquery
|
printer = 7.125
println format("%09.3f", printer)
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands 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).
|
#Jsish
|
Jsish
|
#!/usr/bin/env jsish
/* 4 bit adder simulation, in Jsish */
function not(a) { return a == 1 ? 0 : 1; }
function and(a, b) { return a + b < 2 ? 0 : 1; }
function nand(a, b) { return not(and(a, b)); }
function or(a, b) { return nand(nand(a,a), nand(b,b)); }
function xor(a, b) { return nand(nand(nand(a,b), a), nand(nand(a,b), b)); }
function halfAdder(a, b) { return { carry: and(a, b), sum: xor(a, b) }; }
function fullAdder(a, b, c) {
var h0 = halfAdder(a, b),
h1 = halfAdder(h0.sum, c);
return {carry: or(h0.carry, h1.carry), sum: h1.sum };
}
function fourBitAdder(a, b) {
// set to width 4, pad with 0 if too short and truncate right if too long
var inA = Array(4),
inB = Array(4),
out = Array(4),
i = 4,
pass;
if (a.length < 4) a = '0'.repeat(4 - a.length) + a;
a = a.slice(-4);
if (b.length < 4) b = '0'.repeat(4 - b.length) + b;
b = b.slice(-4);
while (i--) {
var re = /0|1/;
if (a[i] && !re.test(a[i])) throw('bad bit at a[' + i + '] of ' + quote(a[i]));
if (b[i] && !re.test(b[i])) throw('bad bit at b[' + i + '] of ' + quote(b[i]));
inA[i] = a[i] != 1 ? 0 : 1;
inB[i] = b[i] != 1 ? 0 : 1;
}
printf('%s + %s = ', a, b);
// now we can start adding... connecting the constructive blocks
pass = halfAdder(inA[3], inB[3]);
out[3] = pass.sum;
pass = fullAdder(inA[2], inB[2], pass.carry);
out[2] = pass.sum;
pass = fullAdder(inA[1], inB[1], pass.carry);
out[1] = pass.sum;
pass = fullAdder(inA[0], inB[0], pass.carry);
out[0] = pass.sum;
var result = parseInt(pass.carry + out.join(''), 2);
printf('%s %d\n', out.join('') + ' carry ' + pass.carry, result);
return result;
}
if (Interp.conf('unitTest')) {
var bits = [['0000', '0000'], ['0000', '0001'], ['1000', '0001'],
['1010', '0101'], ['1000', '1000'], ['1100', '1100'],
['1111', '1111']];
for (var pair of bits) {
fourBitAdder(pair[0], pair[1]);
}
; fourBitAdder('1', '11');
; fourBitAdder('10001', '01110');
;// fourBitAdder('0002', 'b');
}
/*
=!EXPECTSTART!=
0000 + 0000 = 0000 carry 0 0
0000 + 0001 = 0001 carry 0 1
1000 + 0001 = 1001 carry 0 9
1010 + 0101 = 1111 carry 0 15
1000 + 1000 = 0000 carry 1 16
1100 + 1100 = 1000 carry 1 24
1111 + 1111 = 1110 carry 1 30
fourBitAdder('1', '11') ==> 0001 + 0011 = 0100 carry 0 4
4
fourBitAdder('10001', '01110') ==> 0001 + 1110 = 1111 carry 0 15
15
fourBitAdder('0002', 'b') ==>
PASS!: err = bad bit at a[3] of "2"
=!EXPECTEND!=
*/
|
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.
|
#BASIC
|
BASIC
|
N = 150 : M = 150 : P = 0.03 : F = 0.00003
dim f(N+2,M+2) # 1 tree, 0 empty, 2 fire
dim fn(N+2,M+2)
graphsize N,M
fastgraphics
for x = 1 to N
for y = 1 to M
if rand<0.5 then f[x,y] = 1
next y
next x
while True
for x = 1 to N
for y = 1 to M
if not f[x,y] and rand<P then fn[x,y]=1
if f[x,y]=2 then fn[x,y]=0
if f[x,y]=1 then
fn[x,y] = 1
if f[x-1,y-1]=2 or f[x,y-1]=2 or f[x+1,y-1]=2 then fn[x,y]=2
if f[x-1,y]=2 or f[x+1,y]=2 or rand<F then fn[x,y]=2
if f[x-1,y+1]=2 or f[x,y+1]=2 or f[x+1,y+1]=2 then fn[x,y]=2
end if
# Draw
if fn[x,y]=0 then color black
if fn[x,y]=1 then color green
if fn[x,y]=2 then color yellow
plot x-1,y-1
next y
next x
refresh
for x = 1 to N
for y = 1 to M
f[x,y] = fn[x,y]
next y
next x
end while
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#APL
|
APL
|
∊
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 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.
|
#BCPL
|
BCPL
|
get "libhdr"
static $( randstate = ? $)
let rand() = valof
$( randstate := random(randstate)
resultis randstate >> 7
$)
let showboard(size, board, goal) be
$( writes(" == BOARD == ")
for i=1 to 19 do wrch(' ')
writes(" == GOAL ==*N")
for i=1 to 2
$( writes(" ")
for j=1 to size do writef(" %N",j)
test i=1 for j=1 to 30-2*size do wrch(' ') or wrch('*N')
$)
for row=0 to size-1 for i=1 to 2
$( writef("%C.", 'A'+row)
for col=0 to size-1 do
writef(" %N", (i=1->board,goal)!(row*size+col))
test i=1 for j=1 to 30-2*size do wrch(' ') or wrch('*N')
$)
$)
let readmove(size) = valof
$( let ch = ? and x = ?
writes("Enter row or column, or Q to quit: ")
ch := rdch()
unless ch = '*N' x := rdch() repeatuntil x = '*N'
ch := ch | 32;
if ch = 'q' | ch = endstreamch finish
if 0 <= (ch-'1') < size | 0 <= (ch-'a') < size resultis ch
$) repeat
let flip(size, board, n, col) be
test col
do flipcol(size, board, n)
or fliprow(size, board, n)
and flipcol(size, board, n) be
for i=0 to size-1 do
board!(i*size+n) := 1-board!(i*size+n)
and fliprow(size, board, n) be
for i=0 to size-1 do
board!(n*size+i) := 1-board!(n*size+i)
let makegoal(size, goal) be
for i=0 to size*size-1 do goal!i := rand() & 1
let makeboard(size, board, goal) be
$( for i=0 to size*size-1 do board!i := goal!i
for i=0 to 10+2*(rand() & 15) do
flip(size, board, rand() rem size, rand() & 1)
$)
let win(size, board, goal) = valof
$( for i=0 to size*size-1
unless board!i = goal!i resultis false
resultis true
$)
let play(size, board, goal) be
$( let moves = 0 and move = ?
$( showboard(size, board, goal)
wrch('*N')
if win(size, board, goal)
$( writef("You won in %N moves!*N", moves)
return
$)
moves := moves + 1
move := readmove(size)
test '0' <= move <= '9'
do flipcol(size, board, move-'1')
or fliprow(size, board, move-'a')
$) repeat
$)
let start() be
$( let board = vec 63 and goal = vec 63
let size = ?
writef("****** FLIP THE BITS *******N")
$( writef("Size (3-8)? ")
size := readn()
$) repeatuntil 3 <= size <= 8
writef("Random number seed? ")
randstate := readn()
wrch('*N')
makegoal(size, goal)
makeboard(size, board, goal)
play(size, board, goal)
$)
|
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.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
int i, j;
void fliprow(int **b, int sz, int n)
{
for(i = 0; i < sz; i++)
b[n+1][i] = !b[n+1][i];
}
void flipcol(int **b, int sz, int n)
{
for(i = 1; i <= sz; i++)
b[i][n] = !b[i][n];
}
void initt(int **t, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
t[i][j] = rand()%2;
}
void initb(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
b[i][j] = t[i][j];
for(i = 1; i <= sz; i++)
fliprow(b, sz, rand()%sz+1);
for(i = 0; i < sz; i++)
flipcol(b, sz, rand()%sz);
}
void printb(int **b, int sz)
{
printf(" ");
for(i = 0; i < sz; i++)
printf(" %d", i);
printf("\n");
for(i = 1; i <= sz; i++)
{
printf("%d", i-1);
for(j = 0; j < sz; j++)
printf(" %d", b[i][j]);
printf("\n");
}
printf("\n");
}
int eq(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
if(b[i][j] != t[i][j])
return 0;
return 1;
}
void main()
{
int sz = 3;
int eql = 0;
int mov = 0;
int **t = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
t[i] = malloc(sz*sizeof(int));
int **b = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
b[i] = malloc(sz*sizeof(int));
char roc;
int n;
initt(t, sz);
initb(t, b, sz);
while(eq(t, b, sz))
initb(t, b, sz);
while(!eql)
{
printf("Target: \n");
printb(t, sz);
printf("Board: \n");
printb(b, sz);
printf("What to flip: ");
scanf(" %c", &roc);
scanf(" %d", &n);
switch(roc)
{
case 'r':
fliprow(b, sz, n);
break;
case 'c':
flipcol(b, sz, n);
break;
default:
perror("Please specify r or c and an number");
break;
}
printf("Moves Taken: %d\n", ++mov);
if(eq(t, b, sz))
{
printf("You win!\n");
eql = 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
|
#Comal
|
Comal
|
myprocedure
END // End of main program
PROC myprocedure
PRINT "Hello, this is a procedure"
ENDPROC myprocedure
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#D
|
D
|
import std.stdio;
void main() {
label1:
writeln("I'm in your infinite loop.");
goto label1;
}
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the 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
|
#Python
|
Python
|
import random
from collections import OrderedDict
numbers = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
10 ** 6: 'million',
10 ** 9: 'billion',
10 ** 12: 'trillion',
10 ** 15: 'quadrillion',
10 ** 18: 'quintillion',
10 ** 21: 'sextillion',
10 ** 24: 'septillion',
10 ** 27: 'octillion',
10 ** 30: 'nonillion',
10 ** 33: 'decillion',
10 ** 36: 'undecillion',
10 ** 39: 'duodecillion',
10 ** 42: 'tredecillion',
10 ** 45: 'quattuordecillion',
10 ** 48: 'quinquadecillion',
10 ** 51: 'sedecillion',
10 ** 54: 'septendecillion',
10 ** 57: 'octodecillion',
10 ** 60: 'novendecillion',
10 ** 63: 'vigintillion',
10 ** 66: 'unvigintillion',
10 ** 69: 'duovigintillion',
10 ** 72: 'tresvigintillion',
10 ** 75: 'quattuorvigintillion',
10 ** 78: 'quinquavigintillion',
10 ** 81: 'sesvigintillion',
10 ** 84: 'septemvigintillion',
10 ** 87: 'octovigintillion',
10 ** 90: 'novemvigintillion',
10 ** 93: 'trigintillion',
10 ** 96: 'untrigintillion',
10 ** 99: 'duotrigintillion',
10 ** 102: 'trestrigintillion',
10 ** 105: 'quattuortrigintillion',
10 ** 108: 'quinquatrigintillion',
10 ** 111: 'sestrigintillion',
10 ** 114: 'septentrigintillion',
10 ** 117: 'octotrigintillion',
10 ** 120: 'noventrigintillion',
10 ** 123: 'quadragintillion',
10 ** 153: 'quinquagintillion',
10 ** 183: 'sexagintillion',
10 ** 213: 'septuagintillion',
10 ** 243: 'octogintillion',
10 ** 273: 'nonagintillion',
10 ** 303: 'centillion',
10 ** 306: 'uncentillion',
10 ** 309: 'duocentillion',
10 ** 312: 'trescentillion',
10 ** 333: 'decicentillion',
10 ** 336: 'undecicentillion',
10 ** 363: 'viginticentillion',
10 ** 366: 'unviginticentillion',
10 ** 393: 'trigintacentillion',
10 ** 423: 'quadragintacentillion',
10 ** 453: 'quinquagintacentillion',
10 ** 483: 'sexagintacentillion',
10 ** 513: 'septuagintacentillion',
10 ** 543: 'octogintacentillion',
10 ** 573: 'nonagintacentillion',
10 ** 603: 'ducentillion',
10 ** 903: 'trecentillion',
10 ** 1203: 'quadringentillion',
10 ** 1503: 'quingentillion',
10 ** 1803: 'sescentillion',
10 ** 2103: 'septingentillion',
10 ** 2403: 'octingentillion',
10 ** 2703: 'nongentillion',
10 ** 3003: 'millinillion'
}
numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))
def string_representation(i: int) -> str:
"""
Return the english string representation of an integer
"""
if i == 0:
return 'zero'
words = ['negative'] if i < 0 else []
working_copy = abs(i)
for key, value in numbers.items():
if key <= working_copy:
times = int(working_copy / key)
if key >= 100:
words.append(string_representation(times))
words.append(value)
working_copy -= times * key
if working_copy == 0:
break
return ' '.join(words)
def next_phrase(i: int):
"""
Generate all the phrases
"""
while not i == 4: # Generate phrases until four is reached
str_i = string_representation(i)
len_i = len(str_i)
yield str_i, 'is', string_representation(len_i)
i = len_i
# the last phrase
yield string_representation(i), 'is', 'magic'
def magic(i: int) -> str:
phrases = []
for phrase in next_phrase(i):
phrases.append(' '.join(phrase))
return f'{", ".join(phrases)}.'.capitalize()
if __name__ == '__main__':
for j in (random.randint(0, 10 ** 3) for i in range(5)):
print(j, ':\n', magic(j), '\n')
for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):
print(j, ':\n', magic(j), '\n')
|
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.
|
#ALGOL_W
|
ALGOL W
|
begin
% prints a Floyd's Triangle with n lines %
procedure floydsTriangle ( integer value n ) ;
begin
% the triangle should be left aligned with the individual numbers %
% right-aligned with only one space before the number in the final %
% row %
% calculate the highest number that will be printed %
% ( the sum of the integeregers 1, 2, ... n ) %
integer array widths( 1 :: n );
integer maxNumber, number;
maxNumber := ( n * ( n + 1 ) ) div 2;
% determine the widths required to print the numbers of the final row %
number := maxNumber;
for col := n step -1 until 1 do begin
integer v, w;
w := 0;
v := number;
number := number - 1;
while v > 0 do begin
w := w + 1;
v := v div 10
end while_v_gt_0 ;
widths( col ) := w
end for_col;
% print the triangle %
number := 0;
for row := 1 until n do begin
for col := 1 until row do begin
number := number + 1;
writeon( i_w := widths( col ), s_w := 0, " ", number )
end for_col ;
write()
end for_row
end; % floyds triangle %
floydsTriangle( 5 );
write();
floydsTriangle( 14 )
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.
|
#Perl
|
Perl
|
open $in, '<', 'flr-infile.dat';
open $out, '>', 'flr-outfile.dat';
while ($n=sysread($in, $record, 80)) { # read in fixed sized binary chunks
syswrite $out, reverse $record; # write reversed records to file
print reverse($record)."\n" # display reversed records, line-by-line
}
close $out;
|
http://rosettacode.org/wiki/Fixed_length_records
|
Fixed length records
|
Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, 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.
|
#Phix
|
Phix
|
without js -- file i/o
constant sample_text = """
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 RT MARGIN"""
constant indat = "infile.dat",
outdat = "outfile.dat"
if not file_exists(indat) then
object text = get_text("sample.txt")
if text=-1 then text = sample_text end if
sequence s = split(text,'\n')
integer fn = open(indat,"wb")
for i=1 to length(s) do
puts(fn,s[i]&repeat(' ',80-length(s[i])))
end for
close(fn)
printf(1,"%s created (%d bytes)\n",{indat,get_file_size(indat)})
end if
function get_block(integer fn, size)
string res = ""
for i=1 to size do
res &= getc(fn)
end for
return res
end function
integer fn = open(indat,"rb"),
isize = get_file_size(indat)
puts(1,"reversed:\n")
for i=1 to isize by 80 do
?reverse(get_block(fn,80))
end for
close(fn)
-- Bonus part, 16*64 (=1024) block handling:
procedure put_block(integer fn, sequence lines)
lines &= repeat("",16-length(lines))
for i=1 to length(lines) do
string li = lines[i]
if length(li)>64 then
li = li[1..64]
else
li &= repeat(' ',64-length(li))
end if
puts(fn,li)
end for
end procedure
fn = open(outdat,"wb")
put_block(fn,split(sample_text,'\n'))
close(fn)
integer osize = get_file_size(outdat)
printf(1,"\n%s created (%d bytes):\n",{outdat,osize})
fn = open(outdat,"rb")
sequence lines = {}
for i=1 to osize by 64 do
string line = get_block(fn,64)
?line
lines = append(lines,trim_tail(line,' '))
end for
lines = trim_tail(lines,{""})
puts(1,"\ntrimmed:\n")
pp(lines,{pp_Nest,1})
{} = delete_file(indat) -- (for consistent 2nd run)
|
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)
|
#Elixir
|
Elixir
|
defmodule Floyd_Warshall do
def main(n, edge) do
{dist, next} = setup(n, edge)
{dist, next} = shortest_path(n, dist, next)
print(n, dist, next)
end
defp setup(n, edge) do
big = 1.0e300
dist = for i <- 1..n, j <- 1..n, into: %{}, do: {{i,j},(if i==j, do: 0, else: big)}
next = for i <- 1..n, j <- 1..n, into: %{}, do: {{i,j}, nil}
Enum.reduce(edge, {dist,next}, fn {u,v,w},{dst,nxt} ->
{ Map.put(dst, {u,v}, w), Map.put(nxt, {u,v}, v) }
end)
end
defp shortest_path(n, dist, next) do
(for k <- 1..n, i <- 1..n, j <- 1..n, do: {k,i,j})
|> Enum.reduce({dist,next}, fn {k,i,j},{dst,nxt} ->
if dst[{i,j}] > dst[{i,k}] + dst[{k,j}] do
{Map.put(dst, {i,j}, dst[{i,k}] + dst[{k,j}]), Map.put(nxt, {i,j}, nxt[{i,k}])}
else
{dst, nxt}
end
end)
end
defp print(n, dist, next) do
IO.puts "pair dist path"
for i <- 1..n, j <- 1..n, i != j,
do: :io.format "~w -> ~w ~4w ~s~n", [i, j, dist[{i,j}], path(next, i, j)]
end
defp path(next, i, j), do: path(next, i, j, [i]) |> Enum.join(" -> ")
defp path(_next, i, i, list), do: Enum.reverse(list)
defp path(next, i, j, list) do
u = next[{i,j}]
path(next, u, j, [u | list])
end
end
edge = [{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}]
Floyd_Warshall.main(4, edge)
|
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
|
#PowerShell
|
PowerShell
|
function multiply {
return $args[0] * $args[1]
}
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer 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.)
|
#IDL
|
IDL
|
print,(x = randomu(seed,8)*100)
15.1473 58.0953 82.7465 16.8637 97.7182 59.7856 17.7699 74.9154
print,ts_diff(x,1)
-42.9479 -24.6513 65.8828 -80.8545 37.9326 42.0157 -57.1455 0.000000
print,ts_diff(x,2)
-18.2967 -90.5341 146.737 -118.787 -4.08316 99.1613 0.000000 0.000000
print,ts_diff(x,3)
72.2374 -237.271 265.524 -114.704 -103.244 0.000000 0.000000 0.000000
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#X10
|
X10
|
class HelloWorld {
public static def main(args:Rail[String]):void {
if (args.size < 1) {
Console.OUT.println("Hello world!");
return;
}
}
}
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref savelog symbols binary
import java.text.MessageFormat
sevenPointOneTwoFive = double 7.125
-- using NetRexx Built-In Functions (BIFs)
say Rexx(sevenPointOneTwoFive).format(5, 3).changestr(' ', '0')
-- using Java library constructs
System.out.printf('%09.3f\n', [Double(sevenPointOneTwoFive)])
say MessageFormat.format('{0,number,#00000.###}', [Double(sevenPointOneTwoFive)])
return
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Nim
|
Nim
|
import strformat
const r = 7.125
echo r
echo fmt"{-r:9.3f}"
echo fmt"{r:9.3f}"
echo fmt"{-r:09.3f}"
echo fmt"{r:09.3f}"
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands 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).
|
#Julia
|
Julia
|
using Printf
xor{T<:Bool}(a::T, b::T) = (a&~b)|(~a&b)
halfadder{T<:Bool}(a::T, b::T) = (xor(a,b), a&b)
function fulladder{T<:Bool}(a::T, b::T, c::T=false)
(s, ca) = halfadder(c, a)
(s, cb) = halfadder(s, b)
(s, ca|cb)
end
function adder(a::BitArray{1}, b::BitArray{1}, c0::Bool=false)
len = length(a)
length(b) == len || error("Addend width mismatch.")
c = c0
s = falses(len)
for i in 1:len
(s[i], c) = fulladder(a[i], b[i], c)
end
(s, c)
end
function adder{T<:Integer}(m::T, n::T, wid::T=4, c0::Bool=false)
a = bitpack(digits(m, 2, wid))[1:wid]
b = bitpack(digits(n, 2, wid))[1:wid]
adder(a, b, c0)
end
Base.bits(n::BitArray{1}) = join(reverse(int(n)), "")
|
http://rosettacode.org/wiki/Forest_fire
|
Forest fire
|
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the 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.
|
#Batch_File
|
Batch File
|
m - length and width of the array
p - probability of a tree growing
f - probability of a tree catching on fire
i - iterations to output
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#AppleScript
|
AppleScript
|
my_flatten({{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}})
on my_flatten(aList)
if class of aList is not list then
return {aList}
else if length of aList is 0 then
return aList
else
return my_flatten(first item of aList) & (my_flatten(rest of aList))
end if
end my_flatten
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 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.
|
#C.2B.2B
|
C++
|
#include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() )
{
display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r;
for( string::iterator i = r.begin(); i != r.end(); i++ )
{
byte ii = ( *i );
if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }
else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }
}
}
cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl;
}
void display()
{ system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); }
void output( string t, byte* f )
{
cout << t << endl;
cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl;
for( int y = 0; y < hei; y++ )
{
cout << static_cast<char>( y + 'a' ) << " ";
for( int x = 0; x < wid; x++ )
cout << static_cast<char>( f[x + y * wid] + 48 ) << " ";
cout << endl;
}
cout << endl << endl;
}
bool solved()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( target[x + y * wid] != field[x + y * wid] ) return false;
return true;
}
void createTarget()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( frnd() < .5f ) target[x + y * wid] = 1;
else target[x + y * wid] = 0;
memcpy( field, target, wid * hei );
}
void flipCol( int c )
{ for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }
void flipRow( int r )
{ for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }
void calcStartPos()
{
int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;
for( int x = 0; x < flips; x++ )
{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }
}
void createField()
{
if( field ){ delete [] field; delete [] target; }
int t = wid * hei; field = new byte[t]; target = new byte[t];
memset( field, 0, t ); memset( target, 0, t ); createTarget();
while( true ) { calcStartPos(); if( !solved() ) break; }
}
float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }
byte* field, *target; int wid, hei;
};
int main( int argc, char* argv[] )
{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#11l
|
11l
|
V (x, xi, y, yi) = (2.0, 0.5, 4.0, 0.25)
V z = x + y
V zi = 1.0 / (x + y)
V multiplier = (n1, n2) -> (m -> @=n1 * @=n2 * m)
V numlist = [x, y, z]
V numlisti = [xi, yi, zi]
print(zip(numlist, numlisti).map((n, inversen) -> multiplier(inversen, n)(.5)))
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#E
|
E
|
escape ej {
...body...
}
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the 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
|
#q
|
q
|
C:``one`two`three`four`five`six`seven`eight`nine`ten,
`eleven`twelve`thirteen`fourteen`fifteen`sixteen`seventeen`eighteen`nineteen / cardinal numbers <20
T:``ten`twenty`thirty`forty`fifty`sixty`seventy`eighty`ninety / tens
M:``thousand`million`billion`trillion`quadrillion`quintillion`sextillion`septillion / magnitudes
st:{ / stringify <1000
$[x<20; C x;
x<100; (T;C)@'10 vs x;
{C[y],`hundred,$[z=0;`;x z]}[.z.s] . 100 vs x] }
s:{$[x=0; "zero"; {" "sv string except[;`]raze x{$[x~`;x;x,y]}'M reverse til count x} st each 1000 vs x]} / stringify
fim:{@[;0;upper],[;"four is magic.\n"] raze 1_{y," is ",x,", "}prior s each(count s@)\[x]} / four is magic
1 raze fim each 0 4 8 16 25 89 365 2586 25865 369854 40000000001; / tests
|
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.
|
#AppleScript
|
AppleScript
|
-- FLOYDs TRIANGLE -----------------------------------------------------------
-- floyd :: Int -> [[Int]]
on floyd(n)
script floydRow
on |λ|(start, row)
{start + row + 1, enumFromTo(start, start + row)}
end |λ|
end script
snd(mapAccumL(floydRow, 1, enumFromTo(0, n - 1)))
end floyd
-- showFloyd :: [[Int]] -> String
on showFloyd(xss)
set ws to map(compose({my succ, my |length|, my show}), |last|(xss))
script aligned
on |λ|(xs)
script pad
on |λ|(w, x)
justifyRight(w, space, show(x))
end |λ|
end script
concat(zipWith(pad, ws, xs))
end |λ|
end script
unlines(map(aligned, xss))
end showFloyd
-- TEST ----------------------------------------------------------------------
on run
script test
on |λ|(n)
showFloyd(floyd(n)) & linefeed
end |λ|
end script
unlines(map(test, {5, 14}))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- compose :: [(a -> a)] -> (a -> a)
on compose(fs)
script
on |λ|(x)
script
on |λ|(f, a)
mReturn(f)'s |λ|(a)
end |λ|
end script
foldr(result, x, fs)
end |λ|
end script
end compose
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- foldr :: (b -> a -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- justifyRight :: Int -> Char -> Text -> Text
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- last :: [a] -> a
on |last|(xs)
if length of xs > 0 then
item -1 of xs
else
missing value
end if
end |last|
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- 'The mapAccumL function behaves like a combination of map and foldl;
-- it applies a function to each element of a list, passing an
-- accumulating parameter from left to right, and returning a final
-- value of this accumulator together with the new list.' (see Hoogle)
-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumL(f, acc, xs)
script
on |λ|(a, x)
tell mReturn(f) to set pair to |λ|(item 1 of a, x)
[item 1 of pair, (item 2 of a) & {item 2 of pair}]
end |λ|
end script
foldl(result, [acc, []], xs)
end mapAccumL
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- snd :: (a, b) -> b
on snd(xs)
if class of xs is list and length of xs > 1 then
item 2 of xs
else
missing value
end if
end snd
-- show :: a -> String
on show(e)
set c to class of e
if c = list then
script serialized
on |λ|(v)
show(v)
end |λ|
end script
"{" & intercalate(", ", map(serialized, e)) & "}"
else if c = record then
script showField
on |λ|(kv)
set {k, v} to kv
k & ":" & show(v)
end |λ|
end script
"{" & intercalate(", ", ¬
map(showField, zip(allKeys(e), allValues(e)))) & "}"
else if c = date then
("date \"" & e as text) & "\""
else if c = text then
"\"" & e & "\""
else
try
e as text
on error
("«" & c as text) & "»"
end try
end if
end show
-- succ :: Int -> Int
on succ(x)
x + 1
end succ
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith
|
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.
|
#Python
|
Python
|
infile = open('infile.dat', 'rb')
outfile = open('outfile.dat', 'wb')
while True:
onerecord = infile.read(80)
if len(onerecord) < 80:
break
onerecordreversed = bytes(reversed(onerecord))
outfile.write(onerecordreversed)
infile.close()
outfile.close()
|
http://rosettacode.org/wiki/Fixed_length_records
|
Fixed length records
|
Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, 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.
|
#Raku
|
Raku
|
$*OUT = './flr-outfile.dat'.IO.open(:w, :bin) orelse .die; # open a file in binary mode for writing
while my $record = $*IN.read(80) { # read in fixed sized binary chunks
$*OUT.write: $record.=reverse; # write reversed records out to $outfile
$*ERR.say: $record.decode('ASCII'); # display decoded records on STDERR
}
close $*OUT;
|
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)
|
#F.23
|
F#
|
//Floyd's algorithm: Nigel Galloway August 5th 2018
let Floyd (n:'a[]) (g:Map<('a*'a),int>)= //nodes graph(Map of adjacency list)
let ix n g=Seq.init (pown g n) (fun x->List.unfold(fun (a,b)->if a=0 then None else Some(b%g,(a-1,b/g)))(n,x))
let fN w (i,j,k)=match Map.tryFind(i,j) w,Map.tryFind(i,k) w,Map.tryFind(k,j) w with
|(None ,Some j,Some k)->Some(j+k)
|(Some i,Some j,Some k)->if (j+k) < i then Some(j+k) else None
|_ ->None
let n,z=ix 3 (Array.length n)|>Seq.choose(fun (i::j::k::_)->if i<>j&&i<>k&&j<>k then Some(n.[i],n.[j],n.[k]) else None)
|>Seq.fold(fun (n,n') ((i,j,k) as g)->match fN n g with |Some g->(Map.add (i,j) g n,Map.add (i,j) k n')|_->(n,n')) (g,Map.empty)
(n,(fun x y->seq{
let rec fN n g=seq{
match Map.tryFind (n,g) z with
|Some r->yield! fN n r; yield Some r;yield! fN r g
|_->yield None}
yield! fN x y |> Seq.choose id; yield y}))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Processing
|
Processing
|
float multiply(float x, float y)
{
return x * y;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Prolog
|
Prolog
|
multiply(A, B, P) :- P is A * B.
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer 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.)
|
#J
|
J
|
fd=: 2&(-~/\)
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer 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.)
|
#Java
|
Java
|
import java.util.Arrays;
public class FD {
public static void main(String args[]) {
double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
System.out.println(Arrays.toString(dif(a, 1)));
System.out.println(Arrays.toString(dif(a, 2)));
System.out.println(Arrays.toString(dif(a, 9)));
System.out.println(Arrays.toString(dif(a, 10))); //let's test
System.out.println(Arrays.toString(dif(a, 11)));
System.out.println(Arrays.toString(dif(a, -1)));
System.out.println(Arrays.toString(dif(a, 0)));
}
public static double[] dif(double[] a, int n) {
if (n < 0)
return null; // if the programmer was dumb
for (int i = 0; i < n && a.length > 0; i++) {
double[] b = new double[a.length - 1];
for (int j = 0; j < b.length; j++){
b[j] = a[j+1] - a[j];
}
a = b; //"recurse"
}
return a;
}
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#X86_Assembly
|
X86 Assembly
|
section .data
msg db 'Hello world!', 0AH
len equ $-msg
section .text
global _start
_start: mov edx, len
mov ecx, msg
mov ebx, 1
mov eax, 4
int 80h
mov ebx, 0
mov eax, 1
int 80h
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Oberon-2
|
Oberon-2
|
Out.Real(7.125, 9, 0);
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Objective-C
|
Objective-C
|
NSLog(@"%09.3f", 7.125);
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands 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).
|
#Kotlin
|
Kotlin
|
// version 1.1.51
val Boolean.I get() = if (this) 1 else 0
val Int.B get() = this != 0
class Nybble(val n3: Boolean, val n2: Boolean, val n1: Boolean, val n0: Boolean) {
fun toInt() = n0.I + n1.I * 2 + n2.I * 4 + n3.I * 8
override fun toString() = "${n3.I}${n2.I}${n1.I}${n0.I}"
}
fun Int.toNybble(): Nybble {
val n = BooleanArray(4)
for (k in 0..3) n[k] = ((this shr k) and 1).B
return Nybble(n[3], n[2], n[1], n[0])
}
fun xorGate(a: Boolean, b: Boolean) = (a && !b) || (!a && b)
fun halfAdder(a: Boolean, b: Boolean) = Pair(xorGate(a, b), a && b)
fun fullAdder(a: Boolean, b: Boolean, c: Boolean): Pair<Boolean, Boolean> {
val (s1, c1) = halfAdder(c, a)
val (s2, c2) = halfAdder(s1, b)
return s2 to (c1 || c2)
}
fun fourBitAdder(a: Nybble, b: Nybble): Pair<Nybble, Int> {
val (s0, c0) = fullAdder(a.n0, b.n0, false)
val (s1, c1) = fullAdder(a.n1, b.n1, c0)
val (s2, c2) = fullAdder(a.n2, b.n2, c1)
val (s3, c3) = fullAdder(a.n3, b.n3, c2)
return Nybble(s3, s2, s1, s0) to c3.I
}
const val f = "%s + %s = %d %s (%2d + %2d = %2d)"
fun test(i: Int, j: Int) {
val a = i.toNybble()
val b = j.toNybble()
val (r, c) = fourBitAdder(a, b)
val s = c * 16 + r.toInt()
println(f.format(a, b, c, r, i, j, s))
}
fun main(args: Array<String>) {
println(" A B C R I J S")
for (i in 0..15) {
for (j in i..minOf(i + 1, 15)) test(i, j)
}
}
|
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.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <pthread.h>
#include <SDL.h>
// defaults
#define PROB_TREE 0.55
#define PROB_F 0.00001
#define PROB_P 0.001
#define TIMERFREQ 100
#ifndef WIDTH
# define WIDTH 640
#endif
#ifndef HEIGHT
# define HEIGHT 480
#endif
#ifndef BPP
# define BPP 32
#endif
#if BPP != 32
#warning This program could not work with BPP different from 32
#endif
uint8_t *field[2], swapu;
double prob_f = PROB_F, prob_p = PROB_P, prob_tree = PROB_TREE;
enum cell_state {
VOID, TREE, BURNING
};
// simplistic random func to give [0, 1)
double prand()
{
return (double)rand() / (RAND_MAX + 1.0);
}
// initialize the field
void init_field(void)
{
int i, j;
swapu = 0;
for(i = 0; i < WIDTH; i++)
{
for(j = 0; j < HEIGHT; j++)
{
*(field[0] + j*WIDTH + i) = prand() > prob_tree ? VOID : TREE;
}
}
}
// the "core" of the task: the "forest-fire CA"
bool burning_neighbor(int, int);
pthread_mutex_t synclock = PTHREAD_MUTEX_INITIALIZER;
static uint32_t simulate(uint32_t iv, void *p)
{
int i, j;
/*
Since this is called by SDL, "likely"(*) in a separated
thread, we try to avoid corrupted updating of the display
(done by the show() func): show needs the "right" swapu
i.e. the right complete field. (*) what if it is not so?
The following is an attempt to avoid unpleasant updates.
*/
pthread_mutex_lock(&synclock);
for(i = 0; i < WIDTH; i++) {
for(j = 0; j < HEIGHT; j++) {
enum cell_state s = *(field[swapu] + j*WIDTH + i);
switch(s)
{
case BURNING:
*(field[swapu^1] + j*WIDTH + i) = VOID;
break;
case VOID:
*(field[swapu^1] + j*WIDTH + i) = prand() > prob_p ? VOID : TREE;
break;
case TREE:
if (burning_neighbor(i, j))
*(field[swapu^1] + j*WIDTH + i) = BURNING;
else
*(field[swapu^1] + j*WIDTH + i) = prand() > prob_f ? TREE : BURNING;
break;
default:
fprintf(stderr, "corrupted field\n");
break;
}
}
}
swapu ^= 1;
pthread_mutex_unlock(&synclock);
return iv;
}
// the field is a "part" of an infinite "void" region
#define NB(I,J) (((I)<WIDTH)&&((I)>=0)&&((J)<HEIGHT)&&((J)>=0) \
? (*(field[swapu] + (J)*WIDTH + (I)) == BURNING) : false)
bool burning_neighbor(int i, int j)
{
return NB(i-1,j-1) || NB(i-1, j) || NB(i-1, j+1) ||
NB(i, j-1) || NB(i, j+1) ||
NB(i+1, j-1) || NB(i+1, j) || NB(i+1, j+1);
}
// "map" the field into gfx mem
// burning trees are red
// trees are green
// "voids" are black;
void show(SDL_Surface *s)
{
int i, j;
uint8_t *pixels = (uint8_t *)s->pixels;
uint32_t color;
SDL_PixelFormat *f = s->format;
pthread_mutex_lock(&synclock);
for(i = 0; i < WIDTH; i++) {
for(j = 0; j < HEIGHT; j++) {
switch(*(field[swapu] + j*WIDTH + i)) {
case VOID:
color = SDL_MapRGBA(f, 0,0,0,255);
break;
case TREE:
color = SDL_MapRGBA(f, 0,255,0,255);
break;
case BURNING:
color = SDL_MapRGBA(f, 255,0,0,255);
break;
}
*(uint32_t*)(pixels + j*s->pitch + i*(BPP>>3)) = color;
}
}
pthread_mutex_unlock(&synclock);
}
int main(int argc, char **argv)
{
SDL_Surface *scr = NULL;
SDL_Event event[1];
bool quit = false, running = false;
SDL_TimerID tid;
// add variability to the simulation
srand(time(NULL));
// we can change prob_f and prob_p
// prob_f prob of spontaneous ignition
// prob_p prob of birth of a tree
double *p;
for(argv++, argc--; argc > 0; argc--, argv++)
{
if ( strcmp(*argv, "prob_f") == 0 && argc > 1 )
{
p = &prob_f;
} else if ( strcmp(*argv, "prob_p") == 0 && argc > 1 ) {
p = &prob_p;
} else if ( strcmp(*argv, "prob_tree") == 0 && argc > 1 ) {
p = &prob_tree;
} else continue;
argv++; argc--;
char *s = NULL;
double t = strtod(*argv, &s);
if (s != *argv) *p = t;
}
printf("prob_f %lf\nprob_p %lf\nratio %lf\nprob_tree %lf\n",
prob_f, prob_p, prob_p/prob_f,
prob_tree);
if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0 ) return EXIT_FAILURE;
atexit(SDL_Quit);
field[0] = malloc(WIDTH*HEIGHT);
if (field[0] == NULL) exit(EXIT_FAILURE);
field[1] = malloc(WIDTH*HEIGHT);
if (field[1] == NULL) { free(field[0]); exit(EXIT_FAILURE); }
scr = SDL_SetVideoMode(WIDTH, HEIGHT, BPP, SDL_HWSURFACE|SDL_DOUBLEBUF);
if (scr == NULL) {
fprintf(stderr, "SDL_SetVideoMode: %s\n", SDL_GetError());
free(field[0]); free(field[1]);
exit(EXIT_FAILURE);
}
init_field();
tid = SDL_AddTimer(TIMERFREQ, simulate, NULL); // suppose success
running = true;
event->type = SDL_VIDEOEXPOSE;
SDL_PushEvent(event);
while(SDL_WaitEvent(event) && !quit)
{
switch(event->type)
{
case SDL_VIDEOEXPOSE:
while(SDL_LockSurface(scr) != 0) SDL_Delay(1);
show(scr);
SDL_UnlockSurface(scr);
SDL_Flip(scr);
event->type = SDL_VIDEOEXPOSE;
SDL_PushEvent(event);
break;
case SDL_KEYDOWN:
switch(event->key.keysym.sym)
{
case SDLK_q:
quit = true;
break;
case SDLK_p:
if (running)
{
running = false;
pthread_mutex_lock(&synclock);
SDL_RemoveTimer(tid); // ignore failure...
pthread_mutex_unlock(&synclock);
} else {
running = true;
tid = SDL_AddTimer(TIMERFREQ, simulate, NULL);
// suppose success...
}
break;
}
case SDL_QUIT:
quit = true;
break;
}
}
if (running) {
pthread_mutex_lock(&synclock);
SDL_RemoveTimer(tid);
pthread_mutex_unlock(&synclock);
}
free(field[0]); free(field[1]);
exit(EXIT_SUCCESS);
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Arturo
|
Arturo
|
print flatten [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
|
http://rosettacode.org/wiki/Flipping_bits_game
|
Flipping bits game
|
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 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.
|
#Clojure
|
Clojure
|
(defn cols [board]
(mapv vec (apply map list board)))
(defn flipv [v]
(mapv #(if (> % 0) 0 1) v))
(defn flip-row [board n]
(assoc board n (flipv (get board n))))
(defn flip-col [board n]
(cols (flip-row (cols board) n)))
(defn play-rand [board n]
(if (= n 0)
board
(let [f (if (= (rand-int 2) 0) flip-row flip-col)]
(recur (f board (rand-int (count board))) (dec n)))))
(defn rand-binary-vec [size]
(vec (take size (repeatedly #(rand-int 2)))))
(defn rand-binary-board [size]
(vec (take size (repeatedly #(rand-binary-vec size)))))
(defn numbers->letters [coll]
(map #(char (+ 97 %)) coll))
(defn column-labels [size]
(apply str (interpose " " (numbers->letters (range size)))))
(defn print-board [board]
(let [size (count board)]
(println "\t " (column-labels size))
(dotimes [n size] (println (inc n) "\t" (board n)))))
(defn key->move [key]
(let [start (int (first key))
row-value (try (Long/valueOf key) (catch NumberFormatException e))]
(cond
(<= 97 start 122) [:col (- start 97)]
(<= 65 start 90) [:col (- start 65)]
(> row-value 0) [:row (dec row-value)]
:else nil)))
(defn play-game [target-board current-board n]
(println "\nTurn " n)
(print-board current-board)
(if (= target-board current-board)
(println "You win!")
(let [move (key->move (read-line))
axis (first move)
idx (second move)]
(cond
(= axis :row) (play-game target-board (flip-row current-board idx) (inc n))
(= axis :col) (play-game target-board (flip-col current-board idx) (inc n))
:else (println "Quitting!")))))
(defn -main
"Flip the Bits Game!"
[& args]
(if-not (empty? args)
(let [target-board (rand-binary-board (Long/valueOf (first args)))]
(println "Target")
(print-board target-board)
(play-game target-board (play-rand target-board 3) 0))))
|
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
|
First power of 2 that has leading decimal digits of 12
|
(This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define p(L,n) to be the nth-smallest
value of j such that the base ten representation
of 2j begins with the digits of L .
So p(12, 1) = 7 and
p(12, 2) = 80
You are also given that:
p(123, 45) = 12710
Task
find:
p(12, 1)
p(12, 2)
p(123, 45)
p(123, 12345)
p(123, 678910)
display the results here, on this page.
|
#11l
|
11l
|
F p(=l, n, pwr = 2)
l = Int(abs(l))
V digitcount = floor(log(l, 10))
V log10pwr = log(pwr, 10)
V (raised, found) = (-1, 0)
L found < n
raised++
V firstdigits = floor(10 ^ (fract(log10pwr * raised) + digitcount))
I firstdigits == l
found++
R raised
L(l, n) [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]
print(‘p(’l‘, ’n‘) = ’p(l, n))
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#Ada
|
Ada
|
with Ada.Text_IO;
procedure Firstclass is
generic
n1, n2 : Float;
function Multiplier (m : Float) return Float;
function Multiplier (m : Float) return Float is
begin
return n1 * n2 * m;
end Multiplier;
num, inv : array (1 .. 3) of Float;
begin
num := (2.0, 4.0, 6.0);
inv := (1.0/2.0, 1.0/4.0, 1.0/6.0);
for i in num'Range loop
declare
function new_function is new Multiplier (num (i), inv (i));
begin
Ada.Text_IO.Put_Line (Float'Image (new_function (0.5)));
end;
end loop;
end Firstclass;
|
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
|
First-class functions/Use numbers analogously
|
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
|
#ALGOL_68
|
ALGOL 68
|
REAL
x := 2,
xi := 0.5,
y := 4,
yi := 0.25,
z := x + y,
zi := 1 / ( x + y );
MODE F = PROC(REAL)REAL;
PROC multiplier = (REAL n1, n2)F: ((REAL m)REAL: n1 * n2 * m);
# Numbers as members of collections #
[]REAL num list = (x, y, z),
inv num list = (xi, yi, zi);
# Apply numbers from list #
FOR key TO UPB num list DO
REAL n = num list[key],
inv n = inv num list[key];
print ((multiplier(inv n, n)(.5), new line))
OD
|
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
|
#Erlang
|
Erlang
|
: checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
2DUP @ 0 SWAP WITHIN IF
SWAP 1+ CELLS +
ELSE
1 THROW
THEN ;
8 checked-array myarray
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;
|
http://rosettacode.org/wiki/Flow-control_structures
|
Flow-control structures
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Structures and Loop Structures have their own articles/categories.
Related tasks
Conditional Structures
Loop Structures
|
#Forth
|
Forth
|
: checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
2DUP @ 0 SWAP WITHIN IF
SWAP 1+ CELLS +
ELSE
1 THROW
THEN ;
8 checked-array myarray
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the 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
|
#R
|
R
|
# provided by neonira
integerToText <- function(value_n_1) {
english_words_for_numbers <- list(
simples = c(
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
),
tens = c('twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'),
powers = c(
'hundred' = 100,
'thousand' = 1000,
'million' = 1000000,
'billion' = 1000000000,
'trillion' = 1000000000000,
'quadrillion' = 1000000000000000,
'quintillion' = 1000000000000000000
)
)
buildResult <- function(x_s) {
if (value_n_1 < 0) return(paste('minus', x_s))
x_s
}
withDash <- function(a_s, b_s) paste(a_s, b_s, sep = '-')
val <- abs(value_n_1)
if (val < 20L) return(buildResult(english_words_for_numbers$simples[val + 1L]))
if (val < 100L) {
tens <- val %/% 10L - 1L
reminder <- val %% 10L
if (reminder == 0L) return(buildResult(english_words_for_numbers$ten[tens]))
return(buildResult(withDash(english_words_for_numbers$ten[tens], Recall(reminder))))
}
index <- l <- length(english_words_for_numbers$powers)
for(power in seq_len(l)) {
if (val < english_words_for_numbers$powers[power]) {
index <- power - 1L
break
}
}
f <- Recall(val %/% english_words_for_numbers$powers[index])
reminder <- val %% english_words_for_numbers$powers[index]
if (reminder == 0L) return(buildResult(paste(f, names(english_words_for_numbers$powers)[index])))
buildResult(paste(f, names(english_words_for_numbers$powers)[index], Recall(reminder)))
}
magic <- function(value_n_1) {
text <- vector('character')
while(TRUE) {
r <- integerToText(value_n_1)
nc <- nchar(r)
complement <- ifelse(value_n_1 == 4L, "is magic", paste("is", integerToText(nc)))
text[length(text) + 1L] <- paste(r, complement)
if (value_n_1 == 4L) break
value_n_1 <- nc
}
buildSentence <- function(x_s) paste0(toupper(substr(x_s, 1L, 1L)), substring(x_s, 2L), '.')
buildSentence(paste(text, collapse = ', '))
}
|
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
|
#Racket
|
Racket
|
#lang racket
(require rackunit)
(define smalls
(map symbol->string
'(zero one two three four five six seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen seventeen eighteen nineteen)))
(define tens
(map symbol->string
'(zero ten twenty thirty forty fifty sixty seventy eighty ninety)))
(define larges
(map symbol->string
'(thousand million billion trillion quadrillion quintillion sextillion
septillion octillion nonillion decillion undecillion duodecillion
tredecillion quattuordecillion quindecillion sexdecillion
septendecillion octodecillion novemdecillion vigintillion)))
(define (number->words n)
(define (step div suffix separator [subformat number->words])
(define-values [q r] (quotient/remainder n div))
(define S (if suffix (~a (subformat q) " " suffix) (subformat q)))
(if (zero? r) S (~a S separator (number->words r))))
(cond [(< n 0) (~a "negative " (number->words (- n)))]
[(< n 20) (list-ref smalls n)]
[(< n 100) (step 10 #f "-" (curry list-ref tens))]
[(< n 1000) (step 100 "hundred" " ")]
[else (let loop ([N 1000000] [D 1000] [unit larges])
(cond [(null? unit)
(error 'number->words "number too big: ~e" n)]
[(< n N) (step D (car unit) " ")]
[else (loop (* 1000 N) (* 1000 D) (cdr unit))]))]))
(define (first-cap s)
(~a (string-upcase (substring s 0 1)) (substring s 1)))
(define (magic word [acc null])
(if (equal? word "four")
(string-join (reverse (cons "four is magic." acc)) ", \n")
(let* ([word-len (string-length word)]
[words (number->words word-len)])
(magic words
(cons (string-append word " is " words) acc)))))
(define (number-magic n)
(first-cap (magic (number->words n))))
(for ([n (append (range 11)
'(-10 23 172 20140 100 130 999999 876000000
874143425855745733896030))])
(displayln n)
(displayln (number-magic n))
(newline))
|
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.
|
#Arturo
|
Arturo
|
floyd: function [rowcount][
result: new [[1]]
while [rowcount > size result][
n: inc last last result
row: new []
loop n..n+size last result 'k -> 'row ++ @[k]
'result ++ @[row]
]
return result
]
loop [5 14] 'j [
f: floyd j
loop f 'row -> print map row 'r [pad to :string r 3]
print ""
]
|
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.
|
#REBOL
|
REBOL
|
inp: open %infile.dat
out: open/new %outfile.dat
while [ not empty? line: copy/part inp 80 ][ write out reverse line ]
close inp
close out
|
http://rosettacode.org/wiki/Fixed_length_records
|
Fixed length records
|
Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, 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.
|
#REXX
|
REXX
|
/*REXX pgm reads fixed─length 80 byte records; reverses each record, displays to term. */
iFID= 'FIXEDLEN.TXT' /*the file's filename (used for input).*/
call charin iFID, 1, 0 /*open the file, point rec pointer to 1*/
/* [+] just to be safe, position file.*/
do j=1 while chars(iFID) >= 80 /*read data records of LRECL ≡ eighty. */
@.j= charin(iFID, , 80) /*read a data record of eighty bytes. */
end /*j*/
#= j - 1 /*adjust # of records (J is 1 too high)*/
do k=1 for # /* [↓] process all the records read. */
say reverse(@.k) /* reverse a record and write to term. */
end /*k*/ /*stick a fork in it, we're all done. */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.