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/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
|
#VAX_Assembly
|
VAX Assembly
|
desc: .ascid "Hello World!" ;descriptor (len+addr) and text
.entry hello, ^m<> ;register save mask
pushaq desc ;address of descriptor
calls #1, g^lib$put_output ;call with one argument on stack
ret ;restore registers, clean stack & return
.end hello ;transfer address for linker
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Maxima
|
Maxima
|
deftaylor(f(x), sum(n! * x^n, n, 0, inf))$
taylor(f(x), x, 0, 10);
/ * 1 + x + 2 * x^2 + 6 * x^3 + 24 * x^4 + 120 * x^5 + 720 * x^6 + 5040 * x^7 + 40320 * x^8 + 362880 * x^9 + 3628800 * x^10 + ... * /
taylor(f(x)^2, x, 0, 10);
/ * 1 + 2 * x + 5 * x^2 + 16 * x^3 + 64 * x^4 + 312 * x^5 + 1812 * x^6 + 12288 * x^7 + 95616 * x^8 + 840960 * x^9 + 8254080 * x^10 + ... * /
deftaylor(fcos(x), sum((-1)^n * x^(2 * n) / (2 * n)!, n, 0, inf))$
deftaylor(fsin(x), sum((-1)^n * x^(2 * n + 1) / (2 * n + 1)!, n, 0, inf))$
taylor(fcos(x)^2 + fsin(x)^2, x, 0, 20);
/ * 1 + ... * /
|
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.
|
#Erlang
|
Erlang
|
14> io:fwrite("~9.3.0f~n", [7.125]).
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.
|
#ERRE
|
ERRE
|
PROGRAM FORMATTED
PROCEDURE FORMATTED_PRINT(N,LENGTH,DEC_PLACES->FP$)
LOCAL I,C$,NN$
FORMAT$=STRING$(LENGTH,"#")+"."
FOR I=1 TO DEC_PLACES DO
FORMAT$=FORMAT$+"#"
END FOR
OPEN("O",1,"FORMAT.$$$")
WRITE(#1,FORMAT$;N)
CLOSE(1)
OPEN("I",1,"FORMAT.$$$")
INPUT(LINE,#1,N$)
CLOSE(1)
! add leading zeros
FOR I=1 TO LEN(N$) DO
C$=MID$(N$,I,1)
IF C$=" " OR C$="%" THEN NN$=NN$+"0" ELSE NN$=NN$+C$
END FOR
FP$=RIGHT$("000000000000"+NN$,LENGTH) ! chop to required length
END PROCEDURE
BEGIN
PRINT(CHR$(12);) ! CLS
FOR I=1 TO 10 DO
N=RND(1)*10^(INT(10*RND(1))-2)
FORMATTED_PRINT(N,16,5->FP$)
PRINT("Raw number =";N;TAB(30);"Using custom function =";FP$)
END FOR
END PROGRAM
|
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).
|
#COBOL
|
COBOL
|
program-id. test-add.
environment division.
configuration section.
special-names.
class bin is "0" "1".
data division.
working-storage section.
1 parms.
2 a-in pic 9999.
2 b-in pic 9999.
2 r-out pic 9999.
2 c-out pic 9.
procedure division.
display "Enter 'A' value (4-bits binary): "
with no advancing
accept a-in
if a-in (1:) not bin
display "A is not binary"
stop run
end-if
display "Enter 'B' value (4-bits binary): "
with no advancing
accept b-in
if b-in (1:) not bin
display "B is not binary"
stop run
end-if
call "add-4b" using parms
display "Carry " c-out " result " r-out
stop run
.
end program test-add.
program-id. add-4b.
data division.
working-storage section.
1 wk binary.
2 i pic 9(4).
2 occurs 5.
3 a-reg pic 9.
3 b-reg pic 9.
3 c-reg pic 9.
3 r-reg pic 9.
2 a pic 9.
2 b pic 9.
2 c pic 9.
2 a-not pic 9.
2 b-not pic 9.
2 c-not pic 9.
2 ha-1s pic 9.
2 ha-1c pic 9.
2 ha-1s-not pic 9.
2 ha-1c-not pic 9.
2 ha-2s pic 9.
2 ha-2c pic 9.
2 fa-s pic 9.
2 fa-c pic 9.
linkage section.
1 parms.
2 a-in pic 9999.
2 b-in pic 9999.
2 r-out pic 9999.
2 c-out pic 9.
procedure division using parms.
initialize wk
perform varying i from 1 by 1
until i > 4
move a-in (5 - i:1) to a-reg (i)
move b-in (5 - i:1) to b-reg (i)
end-perform
perform simulate-adder varying i from 1 by 1
until i > 4
move c-reg (5) to c-out
perform varying i from 1 by 1
until i > 4
move r-reg (i) to r-out (5 - i:1)
end-perform
exit program
.
simulate-adder section.
move a-reg (i) to a
move b-reg (i) to b
move c-reg (i) to c
add a -1 giving a-not
add b -1 giving b-not
add c -1 giving c-not
compute ha-1s = function max (
function min ( a b-not )
function min ( b a-not ) )
compute ha-1c = function min ( a b )
add ha-1s -1 giving ha-1s-not
add ha-1c -1 giving ha-1c-not
compute ha-2s = function max (
function min ( c ha-1s-not )
function min ( ha-1s c-not ) )
compute ha-2c = function min ( c ha-1c )
compute fa-s = ha-2s
compute fa-c = function max ( ha-1c ha-2c )
move fa-s to r-reg (i)
move fa-c to c-reg (i + 1)
.
end program add-4b.
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Wart
|
Wart
|
do (fork sleep.1
prn.1)
prn.2
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Wren
|
Wren
|
/* fork.wren */
class C {
foreign static fork()
foreign static usleep(usec)
foreign static wait()
}
var pid = C.fork()
if (pid == 0) {
C.usleep(10000)
System.print("\tchild process: done")
} else if (pid < 0) {
System.print("fork error")
} else {
System.print("waiting for child %(pid)...")
System.print("child %(C.wait()) finished")
}
|
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
|
#AutoHotkey
|
AutoHotkey
|
Four_is_magic(num){
nubmer := num
while (num <> 4)
result .= (res := spell(num)) " is " spell(num := StrLen(res)) ", "
return PrettyNumber(nubmer) " " result "four is magic!"
}
Spell(n) { ; recursive function to spell out the name of a max 36 digit integer, after leading 0s removed
Static p1=" thousand ",p2=" million ",p3=" billion ",p4=" trillion ",p5=" quadrillion ",p6=" quintillion "
, p7=" sextillion ",p8=" septillion ",p9=" octillion ",p10=" nonillion ",p11=" decillion "
, t2="twenty",t3="thirty",t4="forty",t5="fifty",t6="sixty",t7="seventy",t8="eighty",t9="ninety"
, o0="zero",o1="one",o2="two",o3="three",o4="four",o5="five",o6="six",o7="seven",o8="eight"
, o9="nine",o10="ten",o11="eleven",o12="twelve",o13="thirteen",o14="fourteen",o15="fifteen"
, o16="sixteen",o17="seventeen",o18="eighteen",o19="nineteen"
If (11 < d := (StrLen(n)-1)//3) ; #of digit groups of 3
Return "Number too big"
If (d) ; more than 3 digits
Return Spell(SubStr(n,1,-3*d)) p%d% ((s:=SubStr(n,1-3*d)) ? ", " Spell(s) : "")
i := SubStr(n,1,1)
If (n > 99) ; 3 digits
Return o%i% " hundred" ((s:=SubStr(n,2)) ? " " Spell(s) : "")
If (n > 19) ; n = 20..99
Return t%i% ((o:=SubStr(n,2)) ? "-" o%o% : "")
Return o%n% ; n = 0..19
}
PrettyNumber(n) { ; inserts thousands separators into a number string
Return RegExReplace(n, "\B(?=((\d{3})+$))", ",")
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref savelog symbols binary
pi = 3.14159265358979323846264338327950
radiusY = 10
in2ft = 12
ft2yds = 3
in2mm = 25.4
mm2m = 1 / 1000
radiusM = multiply(multiply(radiusY, multiply(multiply(ft2yds, in2ft), in2mm)), mm2m)
say "Area of a circle" radiusY "yds radius: " multiply(multiply(radiusY, radiusY), pi).format(3, 3) "sq. yds"
say radiusY "yds =" radiusM.format(3, 3) "metres"
say "Area of a circle" radiusM.format(3, 3)"m radius:" multiply(multiply(radiusM, radiusM), pi).format(3, 3)"m**2"
/**
* Multiplication function
*/
method multiply(multiplicand, multiplier) public static returns Rexx
product = multiplicand * multiplier
return product
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#BBC_BASIC
|
BBC BASIC
|
DIM A(9)
A() = 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0
PRINT "Original array: " FNshowarray(A())
PROCforward_difference(1, A(), B())
PRINT "Forward diff 1: " FNshowarray(B())
PROCforward_difference(2, A(), C())
PRINT "Forward diff 2: " FNshowarray(C())
PROCforward_difference(9, A(), D())
PRINT "Forward diff 9: " FNshowarray(D())
END
DEF PROCforward_difference(n%, a(), RETURN b())
LOCAL c%, i%, j%
DIM b(DIM(a(),1) - n%)
FOR i% = 0 TO DIM(b(),1)
b(i%) = a(i% + n%)
c% = 1
FOR j% = 1 TO n%
c% = -INT(c% * (n% - j% + 1) / j% + 0.5)
b(i%) += c% * a(i% + n% - j%)
NEXT
NEXT
ENDPROC
DEF FNshowarray(a())
LOCAL i%, a$
FOR i% = 0 TO DIM(a(),1)
a$ += STR$(a(i%)) + ", "
NEXT
= LEFT$(LEFT$(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
|
#VBA
|
VBA
|
Public Sub hello_world_text
Debug.Print "Hello World!"
End Sub
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Nim
|
Nim
|
import rationals, tables
type
Fraction = Rational[int]
FpsKind = enum fpsConst, fpsAdd, fpsSub, fpsMul, fpsDiv, fpsDeriv, fpsInteg
Fps = ref object
kind: FpsKind
s1, s2: Fps
a0: Fraction
cache: Table[Natural, Fraction]
const
Zero: Fraction = 0 // 1
One: Fraction = 1 // 1
DispTerm = 12
XVar = "x"
Super: array['0'..'9', string] = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]
#---------------------------------------------------------------------------------------------------
proc `$`(fract: Fraction): string =
## Return the representation of a fraction without the denominator if it is equal to 1.
if fract.den == 1: $fract.num else: rationals.`$`(fract)
#---------------------------------------------------------------------------------------------------
proc exponent(n: Natural): string =
## Return the representation of an exponent using unicode superscript.
if n == 1: return ""
for d in $n: result.add(Super[d])
####################################################################################################
# FPS.
func newFps*(val = 0): Fps =
## Build a FPS of kind fpsConst using the given integer value.
Fps(kind: fpsConst, a0: val // 1)
#---------------------------------------------------------------------------------------------------
func newFps*(val: Fraction): Fps =
## Build a FPS of kind fpsConst using the given fraction.
Fps(kind: fpsConst, a0: val)
#---------------------------------------------------------------------------------------------------
func newFps*(op: FpsKind; x: Fps; y: Fps = nil): Fps =
## Build a FPS for a unary or binary operation.
Fps(kind: op, s1: x, s2: y, a0: Zero)
#---------------------------------------------------------------------------------------------------
func redefine*(fps: Fps; other: Fps) =
## Redefine a FPS, modifying its kind ans its operands.
fps.kind = other.kind
fps.s1 = other.s1
fps.s2 = other.s2
#---------------------------------------------------------------------------------------------------
## Operations on FPS.
func `+`*(x, y: Fps): Fps = newFps(fpsAdd, x, y)
func `-`*(x, y: Fps): Fps = newFps(fpsSub, x, y)
func `*`*(x, y: Fps): Fps = newFps(fpsMul, x, y)
func `/`*(x, y: Fps): Fps = newFps(fpsDiv, x, y)
func derivative*(x: Fps): Fps = newFps(fpsDeriv, x)
func integral*(x: Fps): Fps = newFps(fpsInteg, x)
#---------------------------------------------------------------------------------------------------
func `[]`*(fps: Fps; n: Natural): Fraction =
## Return the nth term of the FPS.
if n in fps.cache: return fps.cache[n]
case fps.kind
of fpsConst:
result = if n > 0: Zero else: fps.a0
of fpsAdd:
result = fps.s1[n] + fps.s2[n]
of fpsSub:
result = fps.s1[n] - fps.s2[n]
of fpsMul:
result = Zero
for i in 0..n: result += fps.s1[i] * fps.s2[n - i]
of fpsDiv:
let d = fps.s2[0]
if d == Zero: raise newException(DivByZeroDefect, "Division by null fraction")
result = fps.s1[n]
for i in 1..n: result -= fps.s2[i] * fps[n - i] / d
of fpsDeriv:
result = fps.s1[n + 1] * (n + 1)
of fpsInteg:
result = if n > 0: fps.s1[n - 1] / n else: fps.a0
fps.cache[n] = result
#---------------------------------------------------------------------------------------------------
proc `$`*(fps: Fps): string =
## Return the representation of a FPS.
var c = fps[0]
if c != Zero: result &= $c
for i in 1..<DispTerm:
c = fps[i]
if c != Zero:
if c > Zero:
if result.len > 0: result &= " + "
else:
result &= " - "
c = -c
result &= (if c == One: XVar else: $c & XVar) & exponent(i)
if result.len == 0: result &= '0'
result &= " + ..."
#———————————————————————————————————————————————————————————————————————————————————————————————————
# Build cos, sin and tan.
var cos = newFps()
let sin = cos.integral()
let tan = sin / cos
cos.redefine(newFps(1) - sin.integral())
echo "sin(x) = ", sin
echo "cos(x) = ", cos
echo "tan(x) = ", tan
# Check that derivative of sin is cos.
echo "derivative of sin(x) = ", sin.derivative()
# Build exp using recursion.
let exp = newFps()
exp.redefine(newFps(1) + exp.integral())
echo "exp(x) = ", exp
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Euphoria
|
Euphoria
|
constant r = 7.125
printf(1,"%9.3f\n",-r)
printf(1,"%9.3f\n",r)
printf(1,"%-9.3f\n",r)
printf(1,"%09.3f\n",-r)
printf(1,"%09.3f\n",r)
printf(1,"%-09.3f\n",r)
|
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.
|
#F.23
|
F#
|
printfn "%09.3f" 7.125f
|
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).
|
#CoffeeScript
|
CoffeeScript
|
# ATOMIC GATES
not_gate = (bit) ->
[1, 0][bit]
and_gate = (bit1, bit2) ->
bit1 and bit2
or_gate = (bit1, bit2) ->
bit1 or bit2
# COMPOSED GATES
xor_gate = (A, B) ->
X = and_gate A, not_gate(B)
Y = and_gate not_gate(A), B
or_gate X, Y
half_adder = (A, B) ->
S = xor_gate A, B
C = and_gate A, B
[S, C]
full_adder = (C0, A, B) ->
[SA, CA] = half_adder C0, A
[SB, CB] = half_adder SA, B
S = SB
C = or_gate CA, CB
[S, C]
n_bit_adder = (n) ->
(A_bits, B_bits) ->
s = []
C = 0
for i in [0...n]
[S, C] = full_adder C, A_bits[i], B_bits[i]
s.push S
[s, C]
adder = n_bit_adder(4)
console.log adder [1, 0, 1, 0], [0, 1, 1, 0]
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#X86-64_Assembly
|
X86-64 Assembly
|
option casemap:none
windows64 equ 1
linux64 equ 3
ifndef __THREAD_CLASS__
__THREAD_CLASS__ equ 1
if @Platform eq windows64
option dllimport:<kernel32>
CreateThread proto :qword, :qword, :qword, :qword, :dword, :qword
HeapAlloc proto :qword, :dword, :qword
HeapFree proto :qword, :dword, :qword
ExitProcess proto :dword
GetProcessHeap proto
option dllimport:<none>
exit equ ExitProcess
elseif @Platform eq linux64
pthread_create proto :qword, :qword, :qword, :qword
malloc proto :qword
free proto :qword
exit proto :dword
endif
printf proto :qword, :vararg
CLASS thread
CMETHOD createthread
ENDMETHODS
tid dq ?
hThread dq ?
ENDCLASS
METHOD thread, Init, <VOIDARG>, <>
mov rax, thisPtr
ret
ENDMETHOD
METHOD thread, createthread, <VOIDARG>, <>, lpCode:qword, arg:qword
local z:qword,x:qword
mov rbx, thisPtr
assume rbx:ptr thread
mov z, lpCode
mov x, 0
.if arg != 0
mov x, arg
.endif
if @Platform eq windows64
invoke CreateThread, 0, 0, z, x, 0, addr [rbx].tid
.if rax == 0
mov rax, -1
ret
.endif
elseif @Platform eq linux64
invoke pthread_create, addr [rbx].tid, 0, z, x
.if rax != 0
mov rax, -1
ret
.endif
endif
mov [rbx].hThread, rax
assume rbx:nothing
ret
ENDMETHOD
METHOD thread, Destroy, <VOIDARG>, <>
;; We should close all thread handles here..
;; But I don't care. In this example, exit does it for me. :]
ret
ENDMETHOD
endif ;;__THREAD_CLASS__
thChild proto
.data
.code
main proc
local pThread:ptr thread
mov pThread, _NEW(thread)
invoke printf, CSTR("--> Main thread spwaning child thread...",10)
lea rax, thChild
pThread->createthread(rax, 0)
_DELETE(pThread)
;; Just a loop so Exit doesn't foobar the program.
;; No reason to include and call Sleep just for this.. -.-
mov rcx, 20000
@@:
add rax, 1
loop @B
invoke exit, 0
ret
main endp
thChild proc
invoke printf, CSTR("--> Goodbye, World! from a child.... thread.",10)
mov rax, 0
ret
thChild endp
end
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#AWK
|
AWK
|
# syntax: GAWK -f FOUR_IS_MAGIC.AWK
BEGIN {
init_numtowords()
n = split("-1 0 1 2 3 4 5 6 7 8 9 11 21 1995 1000000 1234567890 1100100100100",arr," ")
for (i=1; i<=n; i++) {
a = arr[i]
printf("%s: ",a)
do {
if (a == 4) {
break
}
a = numtowords(a)
b = numtowords(length(a))
printf("%s is %s, ",a,b)
a = length(a)
} while (b !~ /^four$/)
printf("four is magic.\n")
}
exit(0)
}
# source: The AWK Programming Language, page 75
function numtowords(n, minus,str) {
if (n < 0) {
n = n * -1
minus = "minus "
}
if (n == 0) {
str = "zero"
}
else {
str = intowords(n)
}
gsub(/ /," ",str)
gsub(/ $/,"",str)
return(minus str)
}
function intowords(n) {
n = int(n)
if (n >= 1000000000000) {
return intowords(n/1000000000000) " trillion " intowords(n%1000000000000)
}
if (n >= 1000000000) {
return intowords(n/1000000000) " billion " intowords(n%1000000000)
}
if (n >= 1000000) {
return intowords(n/1000000) " million " intowords(n%1000000)
}
if (n >= 1000) {
return intowords(n/1000) " thousand " intowords(n%1000)
}
if (n >= 100) {
return intowords(n/100) " hundred " intowords(n%100)
}
if (n >= 20) {
return tens[int(n/10)] " " intowords(n%10)
}
return(nums[n])
}
function init_numtowords() {
split("one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen",nums," ")
split("ten twenty thirty forty fifty sixty seventy eighty ninety",tens," ")
}
|
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
|
#NewLISP
|
NewLISP
|
> (define (my-multiply a b) (* a b))
(lambda (a b) (* a b))
> (my-multiply 2 3)
6
|
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.)
|
#BQN
|
BQN
|
FDiff ← {{-˜´˘2↕𝕩}⍟𝕨 𝕩}
•Show 1 FDiff 90‿47‿58‿29‿22‿32‿55‿5‿55‿73
•Show 2 FDiff 90‿47‿58‿29‿22‿32‿55‿5‿55‿73
|
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.)
|
#C
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
unsigned int i, j;
double* y;
/* handle two special cases */
if (order >= len) return 0;
y = malloc(sizeof(double) * len);
if (!order) {
memcpy(y, x, sizeof(double) * len);
return y;
}
/* first order diff goes from x->y, later ones go from y->y */
for (j = 0; j < order; j++, x = y)
for (i = 0, len--; i < len; i++)
y[i] = x[i + 1] - x[i];
y = realloc(y, sizeof(double) * len);
return y;
}
int main(void)
{
double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
int i, len = sizeof(x) / sizeof(x[0]);
y = fwd_diff(x, len, 1);
for (i = 0; i < len - 1; i++)
printf("%g ", y[i]);
putchar('\n');
return 0;
}
|
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
|
#VBScript
|
VBScript
|
WScript.Echo "Hello world!"
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#PARI.2FGP
|
PARI/GP
|
sin('x)
cos('x)
|
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.
|
#Factor
|
Factor
|
USE: formatting
7.125 "%09.3f\n" printf
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Fantom
|
Fantom
|
class Main
{
public static Void main()
{
echo (7.125.toStr.padl(9, '0'))
}
}
|
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).
|
#Common_Lisp
|
Common Lisp
|
;; returns a list of bits: '(sum carry)
(defun half-adder (a b)
(list (logxor a b) (logand a b)))
;; returns a list of bits: '(sum, carry)
(defun full-adder (a b c-in)
(let*
((h1 (half-adder c-in a))
(h2 (half-adder (first h1) b)))
(list (first h2) (logior (second h1) (second h2)))))
;; a and b are lists of 4 bits each
(defun 4-bit-adder (a b)
(let*
((add-1 (full-adder (fourth a) (fourth b) 0))
(add-2 (full-adder (third a) (third b) (second add-1)))
(add-3 (full-adder (second a) (second b) (second add-2)))
(add-4 (full-adder (first a) (first b) (second add-3))))
(list
(list (first add-4) (first add-3) (first add-2) (first add-1))
(second add-4))))
(defun main ()
(print (4-bit-adder (list 0 0 0 0) (list 0 0 0 0))) ;; '(0 0 0 0) and 0
(print (4-bit-adder (list 0 0 0 0) (list 1 1 1 1))) ;; '(1 1 1 1) and 0
(print (4-bit-adder (list 1 1 1 1) (list 0 0 0 0))) ;; '(1 1 1 1) and 0
(print (4-bit-adder (list 0 1 0 1) (list 1 1 0 0))) ;; '(0 0 0 1) and 1
(print (4-bit-adder (list 1 1 1 1) (list 1 1 1 1))) ;; '(1 1 1 0) and 1
(print (4-bit-adder (list 1 0 1 0) (list 0 1 0 1))) ;; '(1 1 1 1) and 0
)
(main)
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#XPL0
|
XPL0
|
int Key, Process;
[Key:= SharedMem(4); \allocate 4 bytes of memory common to both processes
Process:= Fork(1); \start one child process
case Process of
0: [Lock(Key); Text(0, "Rosetta"); CrLf(0); Unlock(Key)]; \parent process
1: [Lock(Key); Text(0, "Code"); CrLf(0); Unlock(Key)] \child process
other [Lock(Key); Text(0, "Error"); CrLf(0); Unlock(Key)];
Join(Process); \wait for child process to finish
]
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#zkl
|
zkl
|
zkl: System.cmd("ls &")
|
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
|
#C
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <glib.h>
typedef struct named_number_tag {
const char* name;
uint64_t number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 1000000000000 },
{ "quadrillion", 1000000000000000ULL },
{ "quintillion", 1000000000000000000ULL }
};
const named_number* get_named_number(uint64_t n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_number);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
size_t append_number_name(GString* str, uint64_t n) {
static const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
static const char* tens[] = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
size_t len = str->len;
if (n < 20) {
g_string_append(str, small[n]);
}
else if (n < 100) {
g_string_append(str, tens[n/10 - 2]);
if (n % 10 != 0) {
g_string_append_c(str, '-');
g_string_append(str, small[n % 10]);
}
} else {
const named_number* num = get_named_number(n);
uint64_t p = num->number;
append_number_name(str, n/p);
g_string_append_c(str, ' ');
g_string_append(str, num->name);
if (n % p != 0) {
g_string_append_c(str, ' ');
append_number_name(str, n % p);
}
}
return str->len - len;
}
GString* magic(uint64_t n) {
GString* str = g_string_new(NULL);
for (unsigned int i = 0; ; ++i) {
size_t count = append_number_name(str, n);
if (i == 0)
str->str[0] = g_ascii_toupper(str->str[0]);
if (n == 4) {
g_string_append(str, " is magic.");
break;
}
g_string_append(str, " is ");
append_number_name(str, count);
g_string_append(str, ", ");
n = count;
}
return str;
}
void test_magic(uint64_t n) {
GString* str = magic(n);
printf("%s\n", str->str);
g_string_free(str, TRUE);
}
int main() {
test_magic(5);
test_magic(13);
test_magic(78);
test_magic(797);
test_magic(2739);
test_magic(4000);
test_magic(7893);
test_magic(93497412);
test_magic(2673497412U);
test_magic(10344658531277200972ULL);
return 0;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Nial
|
Nial
|
multiply is operation a b {a * b}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Nim
|
Nim
|
proc multiply(a, b: int): int =
result = 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.)
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)
{
switch (order)
{
case 0u:
return sequence;
case 1u:
return sequence.Skip(1).Zip(sequence, (next, current) => next - current);
default:
return ForwardDifference(ForwardDifference(sequence), order - 1u);
}
}
static void Main()
{
IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };
do
{
Console.WriteLine(string.Join(", ", sequence));
} while ((sequence = ForwardDifference(sequence)).Any());
}
}
|
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
|
#Vedit_macro_language
|
Vedit macro language
|
Message("Hello world!")
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Perl
|
Perl
|
package FPS;
use strict;
use warnings;
use Math::BigRat;
sub new {
my $class = shift;
return bless {@_}, $class unless @_ == 1;
my $arg = shift;
return bless { more => $arg }, $class if 'CODE' eq ref $arg;
return bless { coeff => $arg }, $class if 'ARRAY' eq ref $arg;
bless { coeff => [$arg] }, $class;
}
sub coeff {
my ($self, $i) = @_;
my $cache = ($self->{coeff} ||= []);
my $more = $self->{more};
for my $j ( @$cache .. $i ) {
last unless $more;
$cache->[$j] = $more->($j, $self);
}
$cache->[$i] or 0;
}
sub invert {
my $orig = shift;
ref($orig)->new( sub {
my ($i, $self) = @_;
unless( $i ) {
my $a0 = $orig->coeff(0);
die "Cannot invert power series with zero constant term."
unless $a0;
(Math::BigRat->new(1) / $a0);
} else {
my $sum = 0;
my $terms = $self->{coeff};
for my $j (1 .. $i) {
$sum += $orig->coeff($j) * $terms->[$i - $j];
}
-$terms->[0] * $sum;
}
} );
}
sub fixargs {
my ($x, $y, $swap) = @_;
my $class = ref $x;
$y = $class->new($y) unless UNIVERSAL::isa($y, $class);
($x, $y) = ($y, $x) if $swap;
($class, $x, $y);
}
use overload '+' => sub {
my ($class, $x, $y) = &fixargs;
$class->new( sub { $x->coeff($_[0]) + $y->coeff($_[0]) } );
}, '-' => sub {
my ($class, $x, $y) = &fixargs;
$class->new( sub { $x->coeff($_[0]) - $y->coeff($_[0]) } );
}, '*' => sub {
my ($class, $x, $y) = &fixargs;
$class->new( sub {
my $i = shift;
my $sum = 0;
$sum += $x->coeff($_) * $y->coeff($i-$_) for 0..$i;
$sum;
} );
}, '/' => sub {
my ($class, $x, $y) = &fixargs;
$x * $y->invert;
}, '""' => sub {
my $self = shift;
my $str = $self->coeff(0);
for my $i (1..10) {
my $c = $self->coeff($i);
next unless $c;
$str .= ($c < 0) ? (" - " . (-$c)) : (" + ".$c);
$str .= "x^$i";
}
$str;
};
sub differentiate {
my $orig = shift;
ref($orig)->new( sub {
my $i = shift;
($i+1) * $orig->coeff($i);
} );
}
sub integrate {
my $orig = shift;
ref($orig)->new( coeff => [0], more => sub {
my $i = shift;
$orig->coeff($i-1) / Math::BigRat->new($i);
} );
}
my $sin = __PACKAGE__->new;
my $cos = 1 - $sin->integrate;
%$sin = %{$cos->integrate};
my $tan = $sin / $cos;
my $exp = __PACKAGE__->new();
%$exp = (%{$exp->integrate}, coeff => [1]);
print "sin(x) ~= $sin\n";
print "cos(x) ~= $cos\n";
print "tan(x) ~= $tan\n";
print "exp(x) ~= $exp\n";
print "sin^2 + cos^2 = ", $sin*$sin + $cos*$cos, "\n";
1;
__END__
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Forth
|
Forth
|
\ format 'n' digits of the double word 'd'
: #n ( d n -- d ) 0 ?do # loop ;
\ ud.0 prints an unsigned double
: ud.0 ( d n -- ) <# 1- #n #s #> type ;
\ d.0 prints a signed double
: d.0 ( d n -- ) >r tuck dabs <# r> 1- #n #s rot sign #> type ;
|
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.
|
#Fortran
|
Fortran
|
INTEGER :: number = 7125
WRITE(*,"(I8.8)") number ! Prints 00007125
|
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).
|
#D
|
D
|
import std.stdio, std.traits;
void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3,
in T b0, in T b1, in T b2, in T b3,
out T o0, out T o1,
out T o2, out T o3,
out T overflow) pure nothrow @nogc {
// A XOR using only NOT, AND and OR, as task requires.
static T xor(in T x, in T y) pure nothrow @nogc {
return (~x & y) | (x & ~y);
}
static void halfAdder(in T a, in T b,
out T s, out T c) pure nothrow @nogc {
s = xor(a, b);
// s = a ^ b; // The built-in D xor.
c = a & b;
}
static void fullAdder(in T a, in T b, in T ic,
out T s, out T oc) pure nothrow @nogc {
T ps, pc, tc;
halfAdder(/*in*/a, b, /*out*/ps, pc);
halfAdder(/*in*/ps, ic, /*out*/s, tc);
oc = tc | pc;
}
T zero, tc0, tc1, tc2;
fullAdder(/*in*/a0, b0, zero, /*out*/o0, tc0);
fullAdder(/*in*/a1, b1, tc0, /*out*/o1, tc1);
fullAdder(/*in*/a2, b2, tc1, /*out*/o2, tc2);
fullAdder(/*in*/a3, b3, tc2, /*out*/o3, overflow);
}
void main() {
alias T = size_t;
static assert(isUnsigned!T);
enum T one = T.max,
zero = T.min,
a0 = zero, a1 = one, a2 = zero, a3 = zero,
b0 = zero, b1 = one, b2 = one, b3 = one;
T s0, s1, s2, s3, overflow;
fourBitsAdder(/*in*/ a0, a1, a2, a3,
/*in*/ b0, b1, b2, b3,
/*out*/s0, s1, s2, s3, overflow);
writefln(" a3 %032b", a3);
writefln(" a2 %032b", a2);
writefln(" a1 %032b", a1);
writefln(" a0 %032b", a0);
writefln(" +");
writefln(" b3 %032b", b3);
writefln(" b2 %032b", b2);
writefln(" b1 %032b", b1);
writefln(" b0 %032b", b0);
writefln(" =");
writefln(" s3 %032b", s3);
writefln(" s2 %032b", s2);
writefln(" s1 %032b", s1);
writefln(" s0 %032b", s0);
writefln("overflow %032b", overflow);
}
|
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
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <string>
#include <cctype>
#include <cstdint>
typedef std::uint64_t integer;
const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
const char* tens[] = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
struct named_number {
const char* name_;
integer number_;
};
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 1000000000000 },
{ "quadrillion", 1000000000000000ULL },
{ "quintillion", 1000000000000000000ULL }
};
const named_number& get_named_number(integer n) {
constexpr size_t names_len = std::size(named_numbers);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number_)
return named_numbers[i];
}
return named_numbers[names_len - 1];
}
std::string cardinal(integer n) {
std::string result;
if (n < 20)
result = small[n];
else if (n < 100) {
result = tens[n/10 - 2];
if (n % 10 != 0) {
result += "-";
result += small[n % 10];
}
} else {
const named_number& num = get_named_number(n);
integer p = num.number_;
result = cardinal(n/p);
result += " ";
result += num.name_;
if (n % p != 0) {
result += " ";
result += cardinal(n % p);
}
}
return result;
}
inline char uppercase(char ch) {
return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}
std::string magic(integer n) {
std::string result;
for (unsigned int i = 0; ; ++i) {
std::string text(cardinal(n));
if (i == 0)
text[0] = uppercase(text[0]);
result += text;
if (n == 4) {
result += " is magic.";
break;
}
integer len = text.length();
result += " is ";
result += cardinal(len);
result += ", ";
n = len;
}
return result;
}
void test_magic(integer n) {
std::cout << magic(n) << '\n';
}
int main() {
test_magic(5);
test_magic(13);
test_magic(78);
test_magic(797);
test_magic(2739);
test_magic(4000);
test_magic(7893);
test_magic(93497412);
test_magic(2673497412U);
test_magic(10344658531277200972ULL);
return 0;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#OASYS
|
OASYS
|
method int multiply int x int 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
|
#OASYS_Assembler
|
OASYS Assembler
|
[&MULTIPLY#,A#,B#],A#<,B#<MUL RF
|
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.)
|
#C.2B.2B
|
C++
|
#include <vector>
#include <iterator>
#include <algorithm>
// calculate first order forward difference
// requires:
// * InputIterator is an input iterator
// * OutputIterator is an output iterator
// * The value type of InputIterator is copy-constructible and assignable
// * The value type of InputIterator supports operator -
// * The result type of operator- is assignable to the value_type of OutputIterator
// returns: The iterator following the output sequence
template<typename InputIterator, typename OutputIterator>
OutputIterator forward_difference(InputIterator first, InputIterator last,
OutputIterator dest)
{
// special case: for empty sequence, do nothing
if (first == last)
return dest;
typedef typename std::iterator_traits<InputIterator>::value_type value_type;
value_type temp = *first++;
while (first != last)
{
value_type temp2 = *first++;
*dest++ = temp2 - temp;
temp = temp2;
}
return dest;
}
// calculate n-th order forward difference.
// requires:
// * InputIterator is an input iterator
// * OutputIterator is an output iterator
// * The value type of InputIterator is copy-constructible and assignable
// * The value type of InputIterator supports operator -
// * The result type of operator- is assignable to the value_type of InputIterator
// * The result type of operator- is assignable to the value_type of OutputIterator
// * order >= 0
// returns: The iterator following the output sequence
template<typename InputIterator, typename OutputIterator>
OutputIterator nth_forward_difference(int order,
InputIterator first, InputIterator last,
OutputIterator dest)
{
// special case: If order == 0, just copy input to output
if (order == 0)
return std::copy(first, last, dest);
// second special case: If order == 1, just forward to the first-order function
if (order == 1)
return forward_difference(first, last, dest);
// intermediate results are stored in a vector
typedef typename std::iterator_traits<InputIterator>::value_type value_type;
std::vector<value_type> temp_storage;
// fill the vector with the result of the first order forward difference
forward_difference(first, last, std::back_inserter(temp_storage));
// the next n-2 iterations work directly on the vector
typename std::vector<value_type>::iterator begin = temp_storage.begin(),
end = temp_storage.end();
for (int i = 1; i < order-1; ++i)
end = forward_difference(begin, end, begin);
// the final iteration writes directly to the output iterator
return forward_difference(begin, end, dest);
}
// example usage code
#include <iostream>
int main()
{
double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };
// this stores the results in the vector dest
std::vector<double> dest;
nth_forward_difference(1, array, array+10, std::back_inserter(dest));
// output dest
std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
// however, the results can also be output as they are calculated
nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
// finally, the results can also be written into the original array
// (which of course destroys the original content)
double* end = nth_forward_difference(3, array, array+10, array);
for (double* p = array; p < end; ++p)
std::cout << *p << " ";
std::cout << std::endl;
return 0;
}
|
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
|
#Verbexx
|
Verbexx
|
@SAY "Hello world!";
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Phix
|
Phix
|
with javascript_semantics
enum FPS_UNDEF = 0,
FPS_CONST,
FPS_ADD,
FPS_SUB,
FPS_MUL,
FPS_DIV,
FPS_DERIV,
FPS_INT,
FPS_MAX=$
type fps_type(integer f)
return f>=FPS_UNDEF and f<=FPS_MAX
end type
enum FPS_TYPE, FPS_S1, FPS_S2, FPS_A0
sequence fpss = {}
type fps(object id)
return integer(id) and id>=1 and id<=length(fpss)
end type
type fpsn(object id)
return id=NULL or fps(id)
end type
function fps_new(fps_type ft=FPS_UNDEF, fpsn s1=0, s2=0, atom a0=0)
fpss = append(fpss,{ft,s1,s2,a0})
fps fpsid = length(fpss)
return fpsid
end function
-- as per C, for (eg) self or mutually recursive definitions.
procedure fps_redefine(fps fpsid, fps_type ft, fpsn s1id, s2id, object a0="")
fpss[fpsid][FPS_TYPE] = ft
fpss[fpsid][FPS_S1] = s1id
fpss[fpsid][FPS_S2] = s2id
if atom(a0) then
fpss[fpsid][FPS_A0] = a0
end if
end procedure
function fps_const(atom a0)
fps x = fps_new(FPS_CONST,a0:=a0)
-- (aside: in the above, the ":=a0" refers to the local namespace
-- as usual, whereas "a0:=" refers to the param namespace
-- /inside/ the () of fps_new(), so there is no conflict.)
return x
end function
constant INF = 1e300*1e300,
NAN = -(INF/INF)
/* Taking the n-th term of series. This is where actual work is done. */
function term(fps x, int n)
atom ret = 0
{fps_type ft, fpsn s1id, fpsn s2id, atom a0} = fpss[x]
-- FPS_TYPE, FPS_S1, FPS_S2, FPS_A0 <-- nb above must match
switch ft do
case FPS_CONST: ret := iff(n>0 ? 0 : a0)
case FPS_ADD: ret := term(s1id, n) + term(s2id, n)
case FPS_SUB: ret := term(s1id, n) - term(s2id, n)
case FPS_MUL:
for i=0 to n do
ret += term(s1id, i) * term(s2id, n-i)
end for
case FPS_DIV:
if not term(s2id, 0) then return NAN end if
ret = term(s1id, n)
for i=1 to n do
ret -= term(s2id, i) * term(x, n-i) / term(s2id, 0)
end for
case FPS_DERIV: ret := n * term(s1id, n+1)
case FPS_INT: ret := iff(n=0 ? a0 : term(s1id, n-1)/n)
default: ret := 9/0 -- (fatal error)
end switch
return ret
end function
procedure term9(string txt, fps x)
printf(1,"%s:",{txt})
for i=0 to 9 do printf(1," %g", term(x, i)) end for
printf(1,"\n")
end procedure
procedure main()
fps one = fps_const(1)
fps fcos = fps_new() /* cosine */
fps fsin = fps_new(FPS_INT,fcos) /* sine */
fps ftan = fps_new(FPS_DIV,fsin,fcos) /* tangent */
/* redefine cos to complete the mutual recursion */
fps_redefine(fcos, FPS_SUB, one, fps_new(FPS_INT,fsin))
fps fexp = fps_const(1); /* exponential */
/* make exp recurse on self */
fps_redefine(fexp, FPS_INT, fexp, 0);
term9("Sin",fsin)
term9("Cos",fcos)
term9("Tan",ftan)
term9("Exp",fexp)
end procedure
main()
|
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.
|
#Free_Pascal
|
Free Pascal
|
' FB 1.05.0 Win64
#Include "vbcompat.bi"
Dim s As String = Format(7.125, "00000.0##")
Print s
Sleep
|
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.
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
#Include "vbcompat.bi"
Dim s As String = Format(7.125, "00000.0##")
Print s
Sleep
|
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).
|
#Delphi
|
Delphi
|
program Four_bit_adder;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
Type
TBitAdderOutput = record
S, C: Boolean;
procedure Assign(_s, _C: Boolean);
function ToString: string;
end;
TNibbleBits = array[1..4] of Boolean;
TNibble = record
Bits: TNibbleBits;
procedure Assign(_Bits: TNibbleBits); overload;
procedure Assign(value: byte); overload;
function ToString: string;
end;
TFourBitAdderOutput = record
N: TNibble;
c: Boolean;
procedure Assign(_c: Boolean; _N: TNibbleBits);
function ToString: string;
end;
TLogic = record
class function GateNot(const A: Boolean): Boolean; static;
class function GateAnd(const A, B: Boolean): Boolean; static;
class function GateOr(const A, B: Boolean): Boolean; static;
class function GateXor(const A, B: Boolean): Boolean; static;
end;
TConstructiveBlocks = record
function HalfAdder(const A, B: Boolean): TBitAdderOutput;
function FullAdder(const A, B, CI: Boolean): TBitAdderOutput;
function FourBitAdder(const A, B: TNibble; const CI: Boolean): TFourBitAdderOutput;
end;
{ TBitAdderOutput }
procedure TBitAdderOutput.Assign(_s, _C: Boolean);
begin
s := _s;
c := _C;
end;
function TBitAdderOutput.ToString: string;
begin
Result := 'S' + ord(s).ToString + 'C' + ord(c).ToString;
end;
{ TNibble }
procedure TNibble.Assign(_Bits: TNibbleBits);
var
i: Integer;
begin
for i := 1 to 4 do
Bits[i] := _Bits[i];
end;
procedure TNibble.Assign(value: byte);
var
i: Integer;
begin
value := value and $0F;
for i := 1 to 4 do
Bits[i] := ((value shr (i - 1)) and 1) = 1;
end;
function TNibble.ToString: string;
var
i: Integer;
begin
Result := '';
for i := 4 downto 1 do
Result := Result + ord(Bits[i]).ToString;
end;
{ TFourBitAdderOutput }
procedure TFourBitAdderOutput.Assign(_c: Boolean; _N: TNibbleBits);
begin
N.Assign(_N);
c := _c;
end;
function TFourBitAdderOutput.ToString: string;
begin
Result := N.ToString + ' c=' + ord(c).ToString;
end;
{ TLogic }
class function TLogic.GateAnd(const A, B: Boolean): Boolean;
begin
Result := A and B;
end;
class function TLogic.GateNot(const A: Boolean): Boolean;
begin
Result := not A;
end;
class function TLogic.GateOr(const A, B: Boolean): Boolean;
begin
Result := A or B;
end;
class function TLogic.GateXor(const A, B: Boolean): Boolean;
begin
Result := GateOr(GateAnd(A, GateNot(B)), (GateAnd(GateNot(A), B)));
end;
{ TConstructiveBlocks }
function TConstructiveBlocks.FourBitAdder(const A, B: TNibble; const CI: Boolean):
TFourBitAdderOutput;
var
FA: array[1..4] of TBitAdderOutput;
i: Integer;
begin
FA[1] := FullAdder(A.Bits[1], B.Bits[1], CI);
Result.N.Bits[1] := FA[1].S;
for i := 2 to 4 do
begin
FA[i] := FullAdder(A.Bits[i], B.Bits[i], FA[i - 1].C);
Result.N.Bits[i] := FA[i].S;
end;
Result.C := FA[4].C;
end;
function TConstructiveBlocks.FullAdder(const A, B, CI: Boolean): TBitAdderOutput;
var
HA1, HA2: TBitAdderOutput;
begin
HA1 := HalfAdder(CI, A);
HA2 := HalfAdder(HA1.S, B);
Result.Assign(HA2.S, TLogic.GateOr(HA1.C, HA2.C));
end;
function TConstructiveBlocks.HalfAdder(const A, B: Boolean): TBitAdderOutput;
begin
Result.Assign(TLogic.GateXor(A, B), TLogic.GateAnd(A, B));
end;
var
j, k: Integer;
A, B: TNibble;
Blocks: TConstructiveBlocks;
begin
for k := 0 to 255 do
begin
A.Assign(0);
B.Assign(0);
for j := 0 to 7 do
begin
if j < 4 then
A.Bits[j + 1] := ((1 shl j) and k) > 0
else
B.Bits[j + 1 - 4] := ((1 shl j) and k) > 0;
end;
write(A.ToString, ' + ', B.ToString, ' = ');
Writeln(Blocks.FourBitAdder(A, B, false).ToString);
end;
Writeln;
Readln;
end.
|
http://rosettacode.org/wiki/Four_is_magic
|
Four is magic
|
Task
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic.
Three is five, five is four, four is magic.
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
Some task guidelines
You may assume the input will only contain integer numbers.
Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.)
Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.)
When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand.
When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty.
When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18.
The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
The output can either be the return value from the function, or be displayed from within the function.
You are encouraged, though not mandated to use proper sentence capitalization.
You may optionally support negative numbers. -7 is negative seven.
Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code.
Related tasks
Four is the number of_letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Summarize and say sequence
Spelling of ordinal numbers
De Bruijn sequences
|
#Clojure
|
Clojure
|
(require '[clojure.edn :as edn])
(def names { 0 "zero" 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" 1000000 "million" 1000000000 "billion"
1000000000000 "trillion" 1000000000000000 "quadrillion"
1000000000000000000 "quintillion" })
(def powers-of-10 (reverse (sort (filter #(clojure.string/ends-with? (str %) "00") (keys names)))))
(defn name-of [n]
(let [p (first (filter #(>= n %) powers-of-10))]
(cond
(not (nil? p))
(let [quotient (quot n p)
remainder (rem n p)]
(str (name-of quotient) " " (names p) (if (> remainder 0) (str " " (name-of remainder)))))
(and (nil? p) (> n 20))
(let [remainder (rem n 10)
tens (- n remainder)]
(str (names tens) (if (> remainder 0) (str " " (name-of remainder)))))
true
(names n))))
(defn four-is-magic
([n] (four-is-magic n ""))
([n prefix]
(let [name ((if (empty? prefix) clojure.string/capitalize identity) (name-of n))
new-prefix (str prefix (if (not (empty? prefix)) ", "))]
(if (= n 4)
(str new-prefix name " is magic.")
(let [len (count name)]
(four-is-magic len (str new-prefix name " is " (name-of len))))))))
(defn report [n]
(println (str n ": " (four-is-magic n))))
(defn -main [& args]
(doall (map (comp report edn/read-string) args)))
(if (not= "repl" *command-line-args*)
(apply -main *command-line-args*))
|
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
|
#Oberon-2
|
Oberon-2
|
PROCEDURE Multiply(a, b: INTEGER): INTEGER;
BEGIN
RETURN a * b;
END Multiply;
|
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.)
|
#Clojure
|
Clojure
|
(defn fwd-diff [nums order]
(nth (iterate #(map - (next %) %) nums) order))
|
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
|
#Verilog
|
Verilog
|
module main;
initial begin
$display("Hello world!");
$finish ;
end
endmodule
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#PicoLisp
|
PicoLisp
|
(de lazy Args
(def (car Args)
(list (cadr Args)
(cons 'cache (lit (cons))
(caadr Args)
(cddr Args) ) ) ) )
|
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.
|
#FutureBasic
|
FutureBasic
|
window 1, @"Formatted Numeric Output", (0,0,480,270)
print using "0000#.###";7.125
HandleEvents
|
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.
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
Public Sub Main()
Print Format("7.125", "00000.000")
End
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#Elixir
|
Elixir
|
defmodule RC do
use Bitwise
@bit_size 4
def four_bit_adder(a, b) do # returns pair {sum, carry}
a_bits = binary_string_to_bits(a)
b_bits = binary_string_to_bits(b)
Enum.zip(a_bits, b_bits)
|> List.foldr({[], 0}, fn {a_bit, b_bit}, {acc, carry} ->
{s, c} = full_adder(a_bit, b_bit, carry)
{[s | acc], c}
end)
end
defp full_adder(a, b, c0) do
{s, c} = half_adder(c0, a)
{s, c1} = half_adder(s, b)
{s, bor(c, c1)} # returns pair {sum, carry}
end
defp half_adder(a, b) do
{bxor(a, b), band(a, b)} # returns pair {sum, carry}
end
def int_to_binary_string(n) do
Integer.to_string(n,2) |> String.rjust(@bit_size, ?0)
end
defp binary_string_to_bits(s) do
String.codepoints(s) |> Enum.map(fn bit -> String.to_integer(bit) end)
end
def task do
IO.puts " A B A B C S sum"
Enum.each(0..15, fn a ->
bin_a = int_to_binary_string(a)
Enum.each(0..15, fn b ->
bin_b = int_to_binary_string(b)
{sum, carry} = four_bit_adder(bin_a, bin_b)
:io.format "~2w + ~2w = ~s + ~s = ~w ~s = ~2w~n",
[a, b, bin_a, bin_b, carry, Enum.join(sum), Integer.undigits([carry | sum], 2)]
end)
end)
end
end
RC.task
|
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
|
#Common_Lisp
|
Common Lisp
|
(defun integer-to-text (int)
(format nil "~@(~A~)" (with-output-to-string (out)
(loop for n = int then (length c)
for c = (format nil "~R" n)
while (/= n 4)
do (format out "~A is ~R, " c (length c))
finally (format out "four is magic.")))))
|
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
|
#Objeck
|
Objeck
|
function : Multiply(a : Float, b : Float) ~, Float {
return a * b;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#OCaml
|
OCaml
|
let int_multiply x y = x * y
let float_multiply x y = x *. y
|
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.)
|
#CoffeeScript
|
CoffeeScript
|
forward_difference = (arr, n) ->
# Find the n-th order forward difference for arr using
# a straightforward recursive algorithm.
# Assume arr is integers and n <= arr.length.
return arr if n == 0
arr = forward_difference(arr, n-1)
(arr[i+1] - arr[i] for i in [0...arr.length - 1])
arr = [-1, 0, 1, 8, 27, 64, 125, 216]
for n in [0..arr.length]
console.log n, forward_difference arr, n
|
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
|
#VHDL
|
VHDL
|
LIBRARY std;
USE std.TEXTIO.all;
entity test is
end entity test;
architecture beh of test is
begin
process
variable line_out : line;
begin
write(line_out, string'("Hello world!"));
writeline(OUTPUT, line_out);
wait; -- needed to stop the execution
end process;
end architecture beh;
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Python
|
Python
|
''' \
For a discussion on pipe() and head() see
http://paddy3118.blogspot.com/2009/05/pipe-fitting-with-python-generators.html
'''
from itertools import islice
from fractions import Fraction
from functools import reduce
try:
from itertools import izip as zip # for 2.6
except:
pass
def head(n):
''' return a generator that passes through at most n items
'''
return lambda seq: islice(seq, n)
def pipe(gen, *cmds):
''' pipe(a,b,c,d, ...) -> yield from ...d(c(b(a)))
'''
return reduce(lambda gen, cmd: cmd(gen), cmds, gen)
def sinepower():
n = 0
fac = 1
sign = +1
zero = 0
yield zero
while True:
n +=1
fac *= n
yield Fraction(1, fac*sign)
sign = -sign
n +=1
fac *= n
yield zero
def cosinepower():
n = 0
fac = 1
sign = +1
yield Fraction(1,fac)
zero = 0
while True:
n +=1
fac *= n
yield zero
sign = -sign
n +=1
fac *= n
yield Fraction(1, fac*sign)
def pluspower(*powergenerators):
for elements in zip(*powergenerators):
yield sum(elements)
def minuspower(*powergenerators):
for elements in zip(*powergenerators):
yield elements[0] - sum(elements[1:])
def mulpower(fgen,ggen):
'From: http://en.wikipedia.org/wiki/Power_series#Multiplication_and_division'
a,b = [],[]
for f,g in zip(fgen, ggen):
a.append(f)
b.append(g)
yield sum(f*g for f,g in zip(a, reversed(b)))
def constpower(n):
yield n
while True:
yield 0
def diffpower(gen):
'differentiatiate power series'
next(gen)
for n, an in enumerate(gen, start=1):
yield an*n
def intgpower(k=0):
'integrate power series with constant k'
def _intgpower(gen):
yield k
for n, an in enumerate(gen, start=1):
yield an * Fraction(1,n)
return _intgpower
print("cosine")
c = list(pipe(cosinepower(), head(10)))
print(c)
print("sine")
s = list(pipe(sinepower(), head(10)))
print(s)
# integrate cosine
integc = list(pipe(cosinepower(),intgpower(0), head(10)))
# 1 - (integrate sine)
integs1 = list(minuspower(pipe(constpower(1), head(10)),
pipe(sinepower(),intgpower(0), head(10))))
assert s == integc, "The integral of cos should be sin"
assert c == integs1, "1 minus the integral of sin should be cos"
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Gambas
|
Gambas
|
Public Sub Main()
Print Format("7.125", "00000.000")
End
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#gnuplot
|
gnuplot
|
print sprintf("%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).
|
#Erlang
|
Erlang
|
-module( four_bit_adder ).
-export( [add_bits/3, create/1, task/0] ).
add_bits( Adder, A_bits, B_bits ) ->
Adder ! {erlang:self(), lists:reverse(A_bits), lists:reverse(B_bits)},
receive
{Adder, Sum, Carry} -> {Sum, Carry}
end.
create( How_many_bits ) ->
Full_adders = connect_full_adders( [full_adder_create() || _X <- lists:seq(1, How_many_bits)] ),
erlang:spawn_link( fun() -> bit_adder_loop( Full_adders ) end ).
task() ->
Adder = create( 4 ),
add_bits( Adder, [0,0,1,0], [0,0,1,1] ).
bit_adder_loop( Full_adders ) ->
receive
{Pid, As, Bs} ->
Sum = [full_adder_sum(Adder, A, B) || {Adder, A, B} <- lists:zip3(Full_adders, As, Bs)],
Carry = receive
{carry, C} -> C
end,
Pid ! {erlang:self(), lists:reverse(Sum), Carry},
bit_adder_loop( Full_adders )
end.
connect_full_adders( [Full_adder | T]=Full_adders ) ->
lists:foldl( fun connect_full_adders/2, Full_adder, T ),
Full_adders.
connect_full_adders( Full_adder, Previous_full_adder ) ->
Previous_full_adder ! {carry_to, Full_adder},
Full_adder.
half_adder( A, B ) -> {z_xor(A, B), A band B}.
full_adder( A, B, Carry ) ->
{Sum1, Carry1} = half_adder( A, Carry),
{Sum, Carry2} = half_adder( B, Sum1),
{Sum, Carry1 bor Carry2}.
full_adder_create( ) -> erlang:spawn( fun() -> full_adder_loop({0, no_carry_pid}) end ).
full_adder_loop( {Carry, Carry_to} ) ->
receive
{carry, New_carry} -> full_adder_loop( {New_carry, Carry_to} );
{carry_to, Pid} -> full_adder_loop( {Carry, Pid} );
{add, Pid, A, B} ->
{Sum, New_carry} = full_adder( A, B, Carry ),
Pid ! {sum, erlang:self(), Sum},
full_adder_loop_carry_pid( Carry_to, Pid ) ! {carry, New_carry},
full_adder_loop( {New_carry, Carry_to} )
end.
full_adder_loop_carry_pid( no_carry_pid, Pid ) -> Pid;
full_adder_loop_carry_pid( Pid, _Pid ) -> Pid.
full_adder_sum( Pid, A, B ) ->
Pid ! {add, erlang:self(), A, B},
receive
{sum, Pid, S} -> S
end.
%% xor exists, this is another implementation.
z_xor( A, B ) -> (A band (2+bnot B)) bor ((2+bnot A) band B).
|
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
|
#Delphi
|
Delphi
|
program Four_is_magic;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
// https://rosettacode.org/wiki/Number_names#Delphi
const
smallies: array[1..19] of string = ('one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen',
'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen');
tens: array[2..9] of string = ('twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety');
function domaxies(number: int64): string;
const
maxies: array[0..5] of string = (' thousand', ' million', ' billion',
' trillion', ' quadrillion', ' quintillion');
begin
domaxies := '';
if number >= 0 then
domaxies := maxies[number];
end;
function doHundreds(number: int64): string;
begin
Result := '';
if number > 99 then
begin
Result := smallies[number div 100];
Result := Result + ' hundred';
number := number mod 100;
if number > 0 then
Result := Result + ' and ';
end;
if number >= 20 then
begin
Result := Result + tens[number div 10];
number := number mod 10;
if number > 0 then
Result := Result + '-';
end;
if (0 < number) and (number < 20) then
Result := Result + smallies[number];
end;
function spell(number: int64): string;
var
scaleFactor: int64;
maxieStart, h: int64;
begin
if number = 0 then
exit('zero');
scaleFactor := 1000000000000000000;
Result := '';
if number < 0 then
begin
number := -number;
Result := 'negative ';
end;
maxieStart := 5;
if number < 20 then
exit(smallies[number]);
while scaleFactor > 0 do
begin
if number > scaleFactor then
begin
h := number div scaleFactor;
Result := Result + doHundreds(h) + domaxies(maxieStart);
number := number mod scaleFactor;
if number > 0 then
Result := Result + ', ';
end;
scaleFactor := scaleFactor div 1000;
dec(maxieStart);
end;
end;
//****************************************************\\
const
numbers: array of Int64 = [0, 4, 6, 11, 13, 75, 100, 337, -164, int64.MaxValue];
function fourIsMagic(n: int64): string;
var
s: string;
begin
s := spell(n);
s[1] := upcase(s[1]);
var t := s;
while n <> 4 do
begin
n := s.Length;
s := spell(n);
t := t + ' is ' + s + ', ' + s;
end;
t := t + ' is magic.';
exit(t);
end;
begin
// writeln(spell(4));
for var n in numbers do
writeln(fourIsMagic(n));
readln;
end.
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Octave
|
Octave
|
function r = mult(a, b)
r = a .* b;
endfunction
|
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.)
|
#Common_Lisp
|
Common Lisp
|
(defun forward-difference (list)
(mapcar #'- (rest list) list))
(defun nth-forward-difference (list n)
(setf list (copy-list list))
(loop repeat n do (map-into list #'- (rest list) list))
(subseq list 0 (- (length list) n)))
|
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
|
#Vim_Script
|
Vim Script
|
echo "Hello world!\n"
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Racket
|
Racket
|
#lang lazy
(require racket/match)
;; element-wise addition and subtraction
(define (<+> s1 s2) (map + s1 s2))
(define (<-> s1 s2) (map - s1 s2))
;; element-wise scaling
(define (scale a s) (map (λ (x) (* a x)) s))
;; series multiplication
(define (<*> fs gs)
(match-let ([(cons f ft) (! fs)]
[(cons g gt) (! gs)])
(cons (* f g) (<+> (scale f gt) (<*> ft gs)))))
;; series division
(define (</> fs gs)
(match-letrec ([(cons f ft) (! fs)]
[(cons g gt) (! gs)]
[qs (cons (/ f g) (scale (/ g) (<-> ft (<*> qs gt))))])
qs))
;; integration and differentiation
(define (int f) (map / f (enum 1)))
(define (diff f) (map * (cdr f) (enum 1)))
;; series of natural numbers greater then n
(define (enum n) (cons n (enum (+ 1 n ))))
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Go
|
Go
|
fmt.Printf("%09.3f", 7.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.
|
#Groovy
|
Groovy
|
printf ("%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).
|
#F.23
|
F#
|
type Bit =
| Zero
| One
let bNot = function
| Zero -> One
| One -> Zero
let bAnd a b =
match (a, b) with
| (One, One) -> One
| _ -> Zero
let bOr a b =
match (a, b) with
| (Zero, Zero) -> Zero
| _ -> One
let bXor a b = bAnd (bOr a b) (bNot (bAnd a b))
let bHA a b = bAnd a b, bXor a b
let bFA a b cin =
let (c0, s0) = bHA a b
let (c1, s1) = bHA s0 cin
(bOr c0 c1, s1)
let b4A (a3, a2, a1, a0) (b3, b2, b1, b0) =
let (c1, s0) = bFA a0 b0 Zero
let (c2, s1) = bFA a1 b1 c1
let (c3, s2) = bFA a2 b2 c2
let (c4, s3) = bFA a3 b3 c3
(c4, s3, s2, s1, s0)
printfn "0001 + 0111 ="
b4A (Zero, Zero, Zero, One) (Zero, One, One, One) |> printfn "%A"
|
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
|
#F.23
|
F#
|
//Express an Integer in English Language. Nigel Galloway: September 19th., 2018
let fN=[|[|"";"one";"two";"three";"four";"five";"six";"seven";"eight";"nine"|];
[|"ten";"eleven";"twelve";"thirteen";"fourteen";"fifteen";"sixteen";"seventeen";"eighteen";"nineteen"|];
[|"";"";"twenty";"thirty";"fourty";"fifty";"sixty";"seventy";"eighty";"ninety"|]|]
let rec I2α α β=match α with |α when α<20 ->β+fN.[α/10].[α%10]
|α when α<100 ->I2α (α%10) (β+fN.[2].[α/10]+if α%10>0 then " " else "")
|α when α<1000 ->I2α (α-(α/100)*100) (β+fN.[0].[α/100]+" hunred"+if α%100>0 then " and " else "")
|α when α<1000000->I2α (α%1000) (β+(I2α (α/1000) "")+" thousand"+if α%100=0 then "" else if (α-(α/1000)*1000)<100 then " and " else " ")
|
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
|
#Oforth
|
Oforth
|
: multiply * ;
|
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
|
#Ol
|
Ol
|
(lambda (x y)
(* x y))
|
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.)
|
#D
|
D
|
T[] forwardDifference(T)(in T[] data, in int level) pure nothrow
in {
assert(level >= 0 && level < data.length);
} body {
auto result = data.dup;
foreach (immutable i; 0 .. level)
foreach (immutable j, ref el; result[0 .. $ - i - 1])
el = result[j + 1] - el;
result.length -= level;
return result;
}
void main() {
import std.stdio;
const data = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5];
foreach (immutable level; 0 .. data.length)
forwardDifference(data, level).writeln;
}
|
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
|
#Visual_Basic
|
Visual Basic
|
Option Explicit
Private Declare Function AllocConsole Lib "kernel32.dll" () As Long
Private Declare Function FreeConsole Lib "kernel32.dll" () As Long
'needs a reference set to "Microsoft Scripting Runtime" (scrrun.dll)
Sub Main()
Call AllocConsole
Dim mFSO As Scripting.FileSystemObject
Dim mStdIn As Scripting.TextStream
Dim mStdOut As Scripting.TextStream
Set mFSO = New Scripting.FileSystemObject
Set mStdIn = mFSO.GetStandardStream(StdIn)
Set mStdOut = mFSO.GetStandardStream(StdOut)
mStdOut.Write "Hello world!" & vbNewLine
mStdOut.Write "press enter to quit program."
mStdIn.Read 1
Call FreeConsole
End Sub
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Raku
|
Raku
|
class DerFPS { ... }
class IntFPS { ... }
role FPS {
method coeffs { ... }
method differentiate { DerFPS.new(:x(self)) }
method integrate { IntFPS.new(:x(self)) }
method pretty($n) {
sub super($i) { $i.trans('0123456789' => '⁰¹²³⁴⁵⁶⁷⁸⁹') }
my $str = $.coeffs[0];
for flat 1..$n Z $.coeffs[1..$n] -> $p, $c {
when $c > 0 { $str ~= " + { $c .nude.join: '/'}∙x{super($p)}" }
when $c < 0 { $str ~= " - {-$c .nude.join: '/'}∙x{super($p)}" }
}
$str;
}
}
class ExplicitFPS does FPS { has @.coeffs }
class SumFPS does FPS {
has FPS ($.x, $.y);
method coeffs { $.x.coeffs Z+ $.y.coeffs }
}
class DifFPS does FPS {
has FPS ($.x, $.y);
method coeffs { $.x.coeffs Z- $.y.coeffs }
}
class ProFPS does FPS {
has FPS ($.x, $.y);
method coeffs { (0..*).map: { [+] ($.x.coeffs[0..$_] Z* $.y.coeffs[$_...0]) } }
}
class InvFPS does FPS {
has FPS $.x;
method coeffs {
# see http://en.wikipedia.org/wiki/Formal_power_series#Inverting_series
flat gather {
my @a = $.x.coeffs;
@a[0] != 0 or fail "Cannot invert power series with zero constant term.";
take my @b = (1 / @a[0]);
take @b[$_] = -@b[0] * [+] (@a[1..$_] Z* @b[$_-1...0]) for 1..*;
}
}
}
class DerFPS does FPS {
has FPS $.x;
method coeffs { (1..*).map: { $_ * $.x.coeffs[$_] } }
}
class IntFPS does FPS {
has FPS $.x;
method coeffs { 0, |(0..*).map: { $.x.coeffs[$_] / ($_+1) } }
}
class DeferredFPS does FPS {
has FPS $.realized is rw;
method coeffs { $.realized.coeffs }
}
# some arithmetic operations for formal power series
multi infix:<+>(FPS $x, FPS $y) { SumFPS.new(:$x, :$y) }
multi infix:<->(FPS $x, FPS $y) { DifFPS.new(:$x, :$y) }
multi infix:<*>(FPS $x, FPS $y) { ProFPS.new(:$x, :$y) }
multi infix:</>(FPS $x, FPS $y) { $x * InvFPS.new(:x($y)) }
# an example of a mixed-type operator:
multi infix:<->(Numeric $x, FPS $y) { ExplicitFPS.new(:coeffs(lazy flat $x, 0 xx *)) - $y }
# define sine and cosine in terms of each other
my $sin = DeferredFPS.new;
my $cos = 1 - $sin.integrate;
$sin.realized = $cos.integrate;
# define tangent in terms of sine and cosine
my $tan = $sin / $cos;
say 'sin(x) ≈ ' ~ $sin.pretty(10);
say 'cos(x) ≈ ' ~ $cos.pretty(10);
say 'tan(x) ≈ ' ~ $tan.pretty(10);
|
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.
|
#Haskell
|
Haskell
|
import Text.Printf
main =
printf "%09.3f" 7.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.
|
#hexiscript
|
hexiscript
|
fun format n length
let n tostr n
while len n < length
let n 0 + n
endwhile
println n
endfun
format 7.125 9
|
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).
|
#Forth
|
Forth
|
: "NOT" invert 1 and ;
: "XOR" over over "NOT" and >r swap "NOT" and r> or ;
: halfadder over over and >r "XOR" r> ;
: fulladder halfadder >r swap halfadder r> or ;
: 4bitadder ( a3 a2 a1 a0 b3 b2 b1 b0 -- r3 r2 r1 r0 c)
4 roll 0 fulladder swap >r >r
3 roll r> fulladder swap >r >r
2 roll r> fulladder swap >r fulladder r> r> r> 3 roll
;
: .add4 4bitadder 0 .r 4 0 do i 3 - abs roll 0 .r loop cr ;
|
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
|
#Factor
|
Factor
|
USING: ascii formatting io kernel make math.text.english regexp
sequences ;
IN: rosetta-code.four-is-magic
! Strip " and " and "," from the output of Factor's number>text
! word with a regular expression.
: number>english ( n -- str )
number>text R/ and |,/ "" re-replace ;
! Return the length of the input integer's text form.
! e.g. 1 -> 3
: next-len ( n -- m ) number>english length ;
! Given a starting integer, return the sequence of lengths
! terminating with 4.
! e.g. 1 -> { 1 3 5 4 }
: len-chain ( n -- seq )
[ [ dup 4 = ] [ dup , next-len ] until , ] { } make ;
! Convert a non-four number to its phrase form.
! e.g. 6 -> "six is three, "
: non-four ( n -- str )
number>english dup length number>english
"%s is %s, " sprintf ;
! Convert any number to its phrase form.
! e.g. 4 -> "four is magic."
: phrase ( n -- str )
dup 4 = [ drop "four is magic." ] [ non-four ] if ;
: say-magic ( n -- )
len-chain [ phrase ] map concat capitalize print ;
{ 1 4 -11 100 112719908181724 -612312 } [ say-magic ] each
|
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
|
#Fortran
|
Fortran
|
MODULE FOUR_IS_MAGIC
IMPLICIT NONE
CHARACTER(8), DIMENSION(20) :: SMALL_NUMS
CHARACTER(7), DIMENSION(8) :: TENS
CHARACTER(7) :: HUNDRED
CHARACTER(8) :: THOUSAND
CHARACTER(8) :: MILLION
CHARACTER(8) :: BILLION
CHARACTER(9) :: TRILLION
CHARACTER(11) :: QUADRILLION
CHARACTER(11) :: QUINTILLION
CHARACTER(1) :: SEPARATOR
CHARACTER(1) :: SPACE
CONTAINS
SUBROUTINE INIT_ARRAYS
SMALL_NUMS(1) = "zero"
SMALL_NUMS(2) = "one"
SMALL_NUMS(3) = "two"
SMALL_NUMS(4) = "three"
SMALL_NUMS(5) = "four"
SMALL_NUMS(6) = "five"
SMALL_NUMS(7) = "six"
SMALL_NUMS(8) = "seven"
SMALL_NUMS(9) = "eight"
SMALL_NUMS(10) = "nine"
SMALL_NUMS(11) = "ten"
SMALL_NUMS(12) = "eleven"
SMALL_NUMS(13) = "twelve"
SMALL_NUMS(14) = "thirteen"
SMALL_NUMS(15) = "fourteen"
SMALL_NUMS(16) = "fifteen"
SMALL_NUMS(17) = "sixteen"
SMALL_NUMS(18) = "seventeen"
SMALL_NUMS(19) = "eighteen"
SMALL_NUMS(20) = "nineteen"
TENS(1) = "twenty"
TENS(2) = "thirty"
TENS(3) = "forty"
TENS(4) = "fifty"
TENS(5) = "sixty"
TENS(6) = "seventy"
TENS(7) = "eight"
TENS(8) = "ninety"
HUNDRED = "hundred"
THOUSAND = "thousand"
MILLION = "million"
BILLION = "billion"
TRILLION = "trillion"
QUADRILLION = "quadrillion"
QUINTILLION = "quintillion"
SEPARATOR = "-"
SPACE = " "
END SUBROUTINE INIT_ARRAYS
RECURSIVE FUNCTION STRING_REPRESENTATION(NUM) RESULT(NUM_AS_STR)
INTEGER(16), INTENT(IN) :: NUM
CHARACTER(1000) :: NUM_AS_STR
INTEGER(16), DIMENSION(9) :: COMPONENTS
CALL INIT_ARRAYS()
COMPONENTS = GET_COMPONENTS(NUM)
NUM_AS_STR = TRIM(ADJUSTL(GET_SUBSET(COMPONENTS(9), QUINTILLION)))
NUM_AS_STR = TRIM(NUM_AS_STR) // SPACE // TRIM(ADJUSTL(GET_SUBSET(COMPONENTS(8), QUADRILLION)))
NUM_AS_STR = TRIM(NUM_AS_STR) // SPACE // TRIM(ADJUSTL(GET_SUBSET(COMPONENTS(7), TRILLION)))
NUM_AS_STR = TRIM(NUM_AS_STR) // SPACE // TRIM(ADJUSTL(GET_SUBSET(COMPONENTS(6), BILLION)))
NUM_AS_STR = TRIM(NUM_AS_STR) // SPACE // TRIM(ADJUSTL(GET_SUBSET(COMPONENTS(5), MILLION)))
NUM_AS_STR = TRIM(NUM_AS_STR) // SPACE // TRIM(ADJUSTL(GET_SUBSET(COMPONENTS(4), THOUSAND)))
NUM_AS_STR = TRIM(NUM_AS_STR) // SPACE // TRIM(ADJUSTL(GET_SUBSET(COMPONENTS(3), HUNDRED)))
IF (COMPONENTS(2) .EQ. 1) THEN
NUM_AS_STR = TRIM(ADJUSTL(NUM_AS_STR)) // SPACE // TRIM(ADJUSTL(SMALL_NUMS(10 + COMPONENTS(1) + 1)))
ELSE
IF (COMPONENTS(1) .GT. 0) THEN
IF (COMPONENTS(2) .GT. 0) THEN
NUM_AS_STR = TRIM(ADJUSTL(NUM_AS_STR)) // SPACE // TRIM(ADJUSTL(TENS(COMPONENTS(2) - 1))) // SEPARATOR
NUM_AS_STR = TRIM(ADJUSTL(NUM_AS_STR)) // TRIM(ADJUSTL(SMALL_NUMS(COMPONENTS(1) + 1)))
ELSE
NUM_AS_STR = TRIM(ADJUSTL(NUM_AS_STR)) // SPACE // TRIM(ADJUSTL(SMALL_NUMS(COMPONENTS(1) + 1)))
ENDIF
ELSE IF (COMPONENTS(2) .GT. 0) THEN
NUM_AS_STR = TRIM(ADJUSTL(NUM_AS_STR)) // SPACE // TRIM(ADJUSTL(TENS(COMPONENTS(2) - 1)))
ENDIF
ENDIF
END FUNCTION STRING_REPRESENTATION
FUNCTION GET_COMPONENTS(NUM)
INTEGER(16), INTENT(IN) :: NUM
INTEGER(16), DIMENSION(9) :: GET_COMPONENTS
INTEGER(16) :: I_UNITS
INTEGER(16) :: I_TENS
INTEGER(16) :: I_HUNDREDS
INTEGER(16) :: I_THOUSANDS
INTEGER(16) :: I_MILLIONS
INTEGER(16) :: I_BILLIONS
INTEGER(16) :: I_TRILLIONS
INTEGER(16) :: I_QUADRILLIONS
INTEGER(16) :: I_QUINTILLIONS
REAL(16) DIVIDE_TEMP
I_UNITS = NUM
DIVIDE_TEMP = (I_UNITS - MOD(I_UNITS, 1000000000000000000))/1000000000000000000
I_QUINTILLIONS = FLOOR(DIVIDE_TEMP)
IF (I_QUINTILLIONS .NE. 0) THEN
I_UNITS = I_UNITS - I_QUINTILLIONS*1000000000000000000
ENDIF
DIVIDE_TEMP = (I_UNITS - MOD(I_UNITS, 1000000000000000))/1000000000000000
I_QUADRILLIONS = FLOOR(DIVIDE_TEMP)
IF (I_QUADRILLIONS .NE. 0) THEN
I_UNITS = I_UNITS - I_QUADRILLIONS*1000000000000000
ENDIF
DIVIDE_TEMP = (I_UNITS - MOD(I_UNITS, 1000000000000))/1000000000000
I_TRILLIONS = FLOOR(DIVIDE_TEMP)
IF (I_TRILLIONS .NE. 0) THEN
I_UNITS = I_UNITS - I_TRILLIONS*1000000000000
ENDIF
DIVIDE_TEMP = (I_UNITS - MOD(I_UNITS, 1000000000))/1000000000
I_BILLIONS = FLOOR(DIVIDE_TEMP)
IF (I_BILLIONS .NE. 0) THEN
I_UNITS = I_UNITS - I_BILLIONS*1000000000
ENDIF
DIVIDE_TEMP = (I_UNITS - MOD(I_UNITS, 1000000))/1000000
I_MILLIONS = FLOOR(DIVIDE_TEMP)
IF (I_MILLIONS .NE. 0) THEN
I_UNITS = I_UNITS - I_MILLIONS*1000000
ENDIF
DIVIDE_TEMP = (I_UNITS - MOD(I_UNITS, 1000))/1000
I_THOUSANDS = FLOOR(DIVIDE_TEMP)
IF (I_THOUSANDS .NE. 0) THEN
I_UNITS = I_UNITS - I_THOUSANDS*1000
ENDIF
DIVIDE_TEMP = I_UNITS/1E2
I_HUNDREDS = FLOOR(DIVIDE_TEMP)
IF (I_HUNDREDS .NE. 0) THEN
I_UNITS = I_UNITS - I_HUNDREDS*1E2
ENDIF
DIVIDE_TEMP = I_UNITS/10.
I_TENS = FLOOR(DIVIDE_TEMP)
IF (I_TENS .NE. 0) THEN
I_UNITS = I_UNITS - I_TENS*10
ENDIF
GET_COMPONENTS(1) = I_UNITS
GET_COMPONENTS(2) = I_TENS
GET_COMPONENTS(3) = I_HUNDREDS
GET_COMPONENTS(4) = I_THOUSANDS
GET_COMPONENTS(5) = I_MILLIONS
GET_COMPONENTS(6) = I_BILLIONS
GET_COMPONENTS(7) = I_TRILLIONS
GET_COMPONENTS(8) = I_QUADRILLIONS
GET_COMPONENTS(9) = I_QUINTILLIONS
END FUNCTION GET_COMPONENTS
FUNCTION GET_SUBSET(COUNTER, LABEL) RESULT(OUT_STR)
CHARACTER(*), INTENT(IN) :: LABEL
INTEGER(16), INTENT(IN) :: COUNTER
CHARACTER(100) :: OUT_STR
OUT_STR = ""
IF (COUNTER .GT. 0) THEN
IF (COUNTER .LT. 20) THEN
OUT_STR = SPACE // TRIM(ADJUSTL(SMALL_NUMS(COUNTER + 1)))
ELSE
OUT_STR = SPACE // TRIM(ADJUSTL(STRING_REPRESENTATION(COUNTER)))
ENDIF
OUT_STR = TRIM(ADJUSTL(OUT_STR)) // SPACE // TRIM(LABEL)
ENDIF
END FUNCTION GET_SUBSET
SUBROUTINE FIND_MAGIC(NUM)
INTEGER(16), INTENT(IN) :: NUM
INTEGER(16) :: CURRENT, LEN_SIZE
CHARACTER(1000) :: CURRENT_STR, CURRENT_STR_LEN
CHARACTER(1000) :: OUT_STR
CURRENT = NUM
OUT_STR = ""
DO WHILE (CURRENT .NE. 4)
CURRENT_STR = STRING_REPRESENTATION(CURRENT)
LEN_SIZE = LEN_TRIM(ADJUSTL(CURRENT_STR))
CURRENT_STR_LEN = STRING_REPRESENTATION(LEN_SIZE)
OUT_STR = TRIM(ADJUSTL(OUT_STR)) // SPACE // TRIM(ADJUSTL(CURRENT_STR))
OUT_STR = TRIM(ADJUSTL(OUT_STR)) // " is " // TRIM(ADJUSTL(CURRENT_STR_LEN)) // ","
CURRENT = LEN_SIZE
ENDDO
WRITE(*,*) TRIM(ADJUSTL(OUT_STR)) // SPACE // "four is magic."
END SUBROUTINE FIND_MAGIC
END MODULE FOUR_IS_MAGIC
PROGRAM TEST_NUM_NAME
USE FOUR_IS_MAGIC
IMPLICIT NONE
INTEGER(2) I
INTEGER(16), DIMENSION(10) :: TEST_NUMS = (/5, 13, 78, 797, 2739, 4000, 7893, 93497412, 2673497412, 10344658531277200972/)
CHARACTER(1000) :: NUM_NAME
DO I=1, SIZE(TEST_NUMS)
CALL FIND_MAGIC(TEST_NUMS(I))
ENDDO
END PROGRAM
|
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
|
#OOC
|
OOC
|
multiply: func (a: Double, b: Double) -> Double {
a * b
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#ooRexx
|
ooRexx
|
SAY multiply(5, 6)
EXIT
multiply:
PROCEDURE
PARSE ARG x, y
RETURN x*y
|
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.)
|
#Dart
|
Dart
|
List forwardDifference(List _list) {
for (int i = _list.length - 1; i > 0; i--) {
_list[i] = _list[i] - _list[i - 1];
}
_list.removeRange(0, 1);
return _list;
}
void mainAlgorithms() {
List _intList = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73];
for (int i = _intList.length - 1; i >= 0; i--) {
List _list = forwardDifference(_intList);
print(_list);
}
}
|
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.)
|
#Delphi
|
Delphi
|
pragma.enable("accumulator")
/** Single step. */
def forwardDifference(seq :List) {
return accum [] for i in 0..(seq.size() - 2) {
_.with(seq[i + 1] - seq[i])
}
}
/** Iterative implementation of the goal. */
def nthForwardDifference1(var seq :List, n :(int >= 0)) {
for _ in 1..n { seq := forwardDifference(seq) }
return seq
}
/** Imperative implementation of the goal. */
def nthForwardDifference2(seq :List, n :(int >= 0)) {
def buf := seq.diverge()
def finalSize := seq.size() - n
for lim in (finalSize..!seq.size()).descending() {
for i in 0..!lim {
buf[i] := buf[i + 1] - buf[i]
}
}
return buf.run(0, finalSize)
}
? def sampleData := [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
> for n in 0..10 {
> def r1 := nthForwardDifference1(sampleData, n)
> require(r1 == nthForwardDifference2(sampleData, n))
> println(r1)
> }
|
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
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System
Module HelloWorld
Sub Main()
Console.WriteLine("Hello world!")
End Sub
End Module
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Ruby
|
Ruby
|
# Class implementing the Formal Power Series type.
class Fps
# Initialize the FPS instance.
# When nothing specified, all coefficients are 0.
# When const: specifies n, all coefficients are n.
# When delta: specifies n, a[0] = n, then all higher coefficients are zero.
# When iota: specifies n, coefficients are consecutive integers, beginning with a[0] = n.
# When init: specifies an array, coefficients are the array elements, padded with zeroes.
# When enum: specifies a lazy enumerator, that is used for the internal coefficients enum.
def initialize(const: nil, delta: nil, iota: nil, init: nil, enum: nil)
# Create (or save) the specified coefficient enumerator.
case
when const
@coeffenum = make_const(const)
when delta
@coeffenum = make_delta(delta)
when iota
@coeffenum = make_iota(iota)
when init
@coeffenum = make_init(init)
when enum
@coeffenum = enum
else
@coeffenum = make_const(0)
end
# Extend the coefficient enumerator instance with an element accessor.
@coeffenum.instance_eval do
def [](index)
self.drop(index).first
end
end
end
# Return the coefficient at the given index.
def [](index)
@coeffenum.drop(index).first
end
# Return sum: this FPS plus the given FPS.
def +(other)
other = convert(other)
Fps.new(enum:
Enumerator.new do |yielder, inx: 0|
loop do
yielder.yield(@coeffenum[inx] + other[inx])
inx += 1
end
end.lazy)
end
# Return difference: this FPS minus the given FPS.
def -(other)
other = convert(other)
Fps.new(enum:
Enumerator.new do |yielder, inx: 0|
loop do
yielder.yield(@coeffenum[inx] - other[inx])
inx += 1
end
end.lazy)
end
# Return product: this FPS multiplied by the given FPS.
def *(other)
other = convert(other)
Fps.new(enum:
Enumerator.new do |yielder, inx: 0|
loop do
coeff = (0..inx).reduce(0) { |sum, i| sum + (@coeffenum[i] * other[inx - i]) }
yielder.yield(coeff)
inx += 1
end
end.lazy)
end
# Return quotient: this FPS divided by the given FPS.
def /(other)
other = convert(other)
Fps.new(enum:
Enumerator.new do |yielder, inx: 1|
coeffs = [ Rational(@coeffenum[0], other[0]) ]
yielder.yield(coeffs[-1])
loop do
coeffs <<
Rational(
@coeffenum[inx] -
(1..inx).reduce(0) { |sum, i| sum + (other[i] * coeffs[inx - i]) },
other[0])
yielder.yield(coeffs[-1])
inx += 1
end
end.lazy)
end
# Return the derivative of this FPS.
def deriv()
Fps.new(enum:
Enumerator.new do |yielder, inx: 0|
iota = Fps.new(iota: 1)
loop do
yielder.yield(@coeffenum[inx + 1] * iota[inx])
inx += 1
end
end.lazy)
end
# Return the integral of this FPS.
def integ()
Fps.new(enum:
Enumerator.new do |yielder, inx: 0|
iota = Fps.new(iota: 1)
yielder.yield(Rational(0, 1))
loop do
yielder.yield(Rational(@coeffenum[inx], iota[inx]))
inx += 1
end
end.lazy)
end
# Assign a new value to an existing FPS instance.
def assign(other)
other = convert(other)
@coeffenum = other.get_enum
end
# Coerce a Numeric into an FPS instance.
def coerce(other)
if other.kind_of?(Numeric)
[ Fps.new(delta: other), self ]
else
raise TypeError 'non-numeric can\'t be coerced into FPS type'
end
end
# Convert to Integer. (Truncates to 0th coefficient.)
def to_i()
@coeffenum[0].to_i
end
# Convert to Float. (Truncates to 0th coefficient.)
def to_f()
@coeffenum[0].to_f
end
# Convert to Rational. (Truncates to 0th coefficient.)
def to_r()
@coeffenum[0].to_r
end
# Convert to String the first count terms of the FPS.
def to_s(count = 0)
if count <= 0
super()
else
retstr = ''
count.times do |inx|
coeff = (@coeffenum[inx].to_r.denominator == 1) ? @coeffenum[inx].to_i : @coeffenum[inx]
if !(coeff.zero?)
prefix = (retstr != '') ? ' ' : ''
coeffstr =
((coeff.abs == 1) && (inx != 0)) ? '' : "#{coeff.abs.to_s}#{(inx == 0) ? '' : '*'}"
suffix = (inx == 0) ? '' : (inx == 1) ? 'x' : "x^#{inx}"
if coeff < 0
prefix << ((retstr != '') ? '- ' : '-')
else
prefix << ((retstr != '') ? '+ ' : '')
end
retstr << "#{prefix}#{coeffstr}#{suffix}"
end
end
(retstr == '') ? '0' : retstr
end
end
# Evaluate this FPS at the given x value to the given count of terms.
def eval(x, count)
@coeffenum.first(count).each_with_index.reduce(0) { |sum, (coeff, inx) | sum + coeff * x**inx }
end
# Forward method calls to the @coeffenum instance.
def method_missing(name, *args, &block)
@coeffenum.send(name, *args, &block)
end
# Forward respond_to? to the @coeffenum instance.
def respond_to_missing?(name, incl_priv)
@coeffenum.respond_to?(name, incl_priv)
end
protected
# Return reference to the underlying coefficient enumeration.
def get_enum()
@coeffenum
end
private
# Create a "const" lazy enumerator with the given n.
# All elements are n.
def make_const(n)
Enumerator.new do |yielder|
loop { yielder.yield(n) }
end.lazy
end
# Create a "delta" lazy enumerator with the given n.
# First element is n, then all subsequent elements are zero.
def make_delta(n)
Enumerator.new do |yielder|
yielder.yield(n)
loop { yielder.yield(0) }
end.lazy
end
# Create an "iota" lazy enumerator with the given n.
# Elements are consecutive integers, beginning with n.
def make_iota(n)
Enumerator.new do |yielder, i: n|
loop { yielder.yield(i); i += 1 }
end.lazy
end
# Create an "init" lazy enumerator with the given array.
# Elements are the array elements, padded with zeroes.
def make_init(array)
Enumerator.new do |yielder, inx: -1|
loop { yielder.yield((inx < (array.length - 1)) ? array[inx += 1] : 0) }
end.lazy
end
# Convert a Numeric to an FPS instance, if needed.
def convert(other)
if other.kind_of?(Fps)
other
else
if other.kind_of?(Numeric)
Fps.new(delta: other)
else
raise TypeError 'non-numeric can\'t be converted to FPS type'
end
end
end
end
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#HicEst
|
HicEst
|
WRITE(ClipBoard, Format='i5.5, F4.3') INT(7.125), MOD(7.125, 1) ! 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.
|
#i
|
i
|
concept FixedLengthFormat(value, length) {
string = text(abs(value))
prefix = ""
sign = ""
if value < 0
sign = "-"
end
if #string < length
prefix = "0"*(length-#sign-#string-#prefix)
end
return sign+prefix+string
}
software {
d = 7.125
print(FixedLengthFormat(d, 9))
print(FixedLengthFormat(-d, 9))
}
|
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).
|
#Fortran
|
Fortran
|
module logic
implicit none
contains
function xor(a, b)
logical :: xor
logical, intent(in) :: a, b
xor = (a .and. .not. b) .or. (b .and. .not. a)
end function xor
function halfadder(a, b, c)
logical :: halfadder
logical, intent(in) :: a, b
logical, intent(out) :: c
halfadder = xor(a, b)
c = a .and. b
end function halfadder
function fulladder(a, b, c0, c1)
logical :: fulladder
logical, intent(in) :: a, b, c0
logical, intent(out) :: c1
logical :: c2, c3
fulladder = halfadder(halfadder(c0, a, c2), b, c3)
c1 = c2 .or. c3
end function fulladder
subroutine fourbitadder(a, b, s)
logical, intent(in) :: a(0:3), b(0:3)
logical, intent(out) :: s(0:4)
logical :: c0, c1, c2
s(0) = fulladder(a(0), b(0), .false., c0)
s(1) = fulladder(a(1), b(1), c0, c1)
s(2) = fulladder(a(2), b(2), c1, c2)
s(3) = fulladder(a(3), b(3), c2, s(4))
end subroutine fourbitadder
end module
program Four_bit_adder
use logic
implicit none
logical, dimension(0:3) :: a, b
logical, dimension(0:4) :: s
integer, dimension(0:3) :: ai, bi
integer, dimension(0:4) :: si
integer :: i, j
do i = 0, 15
a(0) = btest(i, 0); a(1) = btest(i, 1); a(2) = btest(i, 2); a(3) = btest(i, 3)
where(a)
ai = 1
else where
ai = 0
end where
do j = 0, 15
b(0) = btest(j, 0); b(1) = btest(j, 1); b(2) = btest(j, 2); b(3) = btest(j, 3)
where(b)
bi = 1
else where
bi = 0
end where
call fourbitadder(a, b, s)
where (s)
si = 1
elsewhere
si = 0
end where
write(*, "(4i1,a,4i1,a,5i1)") ai(3:0:-1), " + ", bi(3:0:-1), " = ", si(4:0:-1)
end do
end do
end program
|
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
|
#FreeBASIC
|
FreeBASIC
|
#define floor(x) ((x*2.0-0.5) Shr 1)
Dim Shared veintes(1 To 20) As String*9 => _
{"zero", "one", "two", "three", "four", "five", "six", _
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", _
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
Dim Shared decenas(1 To 8) As String*7 => _
{"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}
Type myorder
var1 As Double
var2 As String*8
End Type
Dim Shared orders(1 To 4) As myorder => _
{(10^12,"trillion"), (10^9,"billion"), (10^6,"million"), (10^3,"thousand")}
Function centenas(n As Integer) As String
If n < 20 Then
Return veintes((n Mod 20)+1)
Elseif (n Mod 10) = 0 Then
Return decenas((floor(n/10) Mod 10)-1)
End If
Return decenas((floor(n/10) Mod 10)-1) & "-" & veintes((n Mod 10)+1)
End Function
Function miles(n As Integer) As String
If n < 100 Then
Return centenas(n)
Elseif (n Mod 100) = 0 Then
Return veintes((floor(n/100) Mod 20)+1) & " centenas"
End If
Return veintes((floor(n/100) Mod 20)+1) & " centenas " & centenas(n Mod 100)
End Function
Function triplet(n As Integer) As String
Dim As Integer order, high, low
Dim As String nombre, res = ""
For i As Integer = 1 To Ubound(orders)
order = orders(i).var1
nombre = orders(i).var2
high = floor(n/order)
low = (n Mod order)
If high <> 0 Then res &= miles(high) & " " & nombre
n = low
If low = 0 Then Exit For : End If
If Len(res) And high <> 0 Then res &= " "
Next i
If n <> 0 Or res="" Then
res &= miles(floor(n))
End If
Return res
End Function
Function deletrear(n As Integer) As String
Dim As String res = ""
If n < 0 Then
res = "negative "
n = -n
End If
res &= triplet(n)
Return res
End Function
Function fourIsMagic(n As Integer) As String
Dim As String s = deletrear(n)
s = Mid(Ucase(s), 1, 1) & Mid(s, 2, Len(s))
Dim As String t = s
While n <> 4
n = Len(s)
s = deletrear(n)
t &= " is " & s & ", " & s
Wend
t &= " is magic."
Return t
End Function
Dim As Longint tests(1 To 21) = _
{-21, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, _
34, 123, 456, 1024, 1234, 12345, 123456, 1010101}
For i As Integer = 1 To Ubound(tests)
Print Using "#######: &"; tests(i); fourIsMagic(tests(i))
Next i
Sleep
|
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
|
#OpenEdge.2FProgress
|
OpenEdge/Progress
|
FUNCTION multiply RETURNS DEC (a AS DEC , b AS DEC ):
RETURN a * b .
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.)
|
#E
|
E
|
pragma.enable("accumulator")
/** Single step. */
def forwardDifference(seq :List) {
return accum [] for i in 0..(seq.size() - 2) {
_.with(seq[i + 1] - seq[i])
}
}
/** Iterative implementation of the goal. */
def nthForwardDifference1(var seq :List, n :(int >= 0)) {
for _ in 1..n { seq := forwardDifference(seq) }
return seq
}
/** Imperative implementation of the goal. */
def nthForwardDifference2(seq :List, n :(int >= 0)) {
def buf := seq.diverge()
def finalSize := seq.size() - n
for lim in (finalSize..!seq.size()).descending() {
for i in 0..!lim {
buf[i] := buf[i + 1] - buf[i]
}
}
return buf.run(0, finalSize)
}
? def sampleData := [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
> for n in 0..10 {
> def r1 := nthForwardDifference1(sampleData, n)
> require(r1 == nthForwardDifference2(sampleData, n))
> println(r1)
> }
|
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
|
#Viua_VM_assembly
|
Viua VM assembly
|
.function: main/0
text %1 local "Hello World!"
print %1 local
izero %0 local
return
.end
|
http://rosettacode.org/wiki/Formal_power_series
|
Formal power series
|
A power series is an infinite sum of the form
a
0
+
a
1
⋅
x
+
a
2
⋅
x
2
+
a
3
⋅
x
3
+
⋯
{\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots }
The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.
If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.
Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.
As an example, define the power series of sine and cosine in terms of each other using integration, as in
sin
x
=
∫
0
x
cos
t
d
t
{\displaystyle \sin x=\int _{0}^{x}\cos t\,dt}
cos
x
=
1
−
∫
0
x
sin
t
d
t
{\displaystyle \cos x=1-\int _{0}^{x}\sin t\,dt}
Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.
|
#Scheme
|
Scheme
|
(define-syntax lons
(syntax-rules ()
((_ lar ldr) (delay (cons lar (delay ldr))))))
(define (lar lons)
(car (force lons)))
(define (ldr lons)
(force (cdr (force lons))))
(define (lap proc . llists)
(lons (apply proc (map lar llists)) (apply lap proc (map ldr llists))))
(define (take n llist)
(if (zero? n)
(list)
(cons (lar llist) (take (- n 1) (ldr llist)))))
(define (iota n)
(lons n (iota (+ n 1))))
(define (repeat n)
(lons n (repeat n)))
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link printf
procedure main()
every r := &pi | -r | 100-r do {
write(r," <=== no printf")
every p := "|%r|" | "|%9.3r|" | "|%-9.3r|" | "|%0.3r|" | "|%e|" | "|%d|" do
write(sprintf(p,r)," <=== sprintf ",p)
}
end
|
http://rosettacode.org/wiki/Formatted_numeric_output
|
Formatted numeric output
|
Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
|
#IDL
|
IDL
|
n = 7.125
print, n, format='(f08.3)'
;==> 0007.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).
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
sub half_add( byval a as ubyte, byval b as ubyte,_
byref s as ubyte, byref c as ubyte)
s = a xor b
c = a and b
end sub
sub full_add( byval a as ubyte, byval b as ubyte, byval c as ubyte,_
byref s as ubyte, byref g as ubyte )
dim as ubyte x, y, z
half_add( a, c, x, y )
half_add( x, b, s, z )
g = y or z
end sub
sub fourbit_add( byval a3 as ubyte, byval a2 as ubyte, byval a1 as ubyte, byval a0 as ubyte,_
byval b3 as ubyte, byval b2 as ubyte, byval b1 as ubyte, byval b0 as ubyte,_
byref s3 as ubyte, byref s2 as ubyte, byref s1 as ubyte, byref s0 as ubyte,_
byref carry as ubyte )
dim as ubyte c2, c1, c0
full_add(a0, b0, 0, s0, c0)
full_add(a1, b1, c0, s1, c1)
full_add(a2, b2, c1, s2, c2)
full_add(a3, b3, c2, s3, carry )
end sub
dim as ubyte s3, s2, s1, s0, carry
print "1100 + 0011 = ";
fourbit_add( 1, 1, 0, 0, 0, 0, 1, 1, s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0
print "1111 + 0001 = ";
fourbit_add( 1, 1, 1, 1, 0, 0, 0, 1, s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0
print "1111 + 1111 = ";
fourbit_add( 1, 1, 1, 1, 1, 1, 1, 1, s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0
|
http://rosettacode.org/wiki/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
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
"strings"
)
func main() {
for _, n := range [...]int64{
0, 4, 6, 11, 13, 75, 100, 337, -164,
math.MaxInt64,
} {
fmt.Println(fourIsMagic(n))
}
}
func fourIsMagic(n int64) string {
s := say(n)
s = strings.ToUpper(s[:1]) + s[1:]
t := s
for n != 4 {
n = int64(len(s))
s = say(n)
t += " is " + s + ", " + s
}
t += " is magic."
return t
}
// Following is from https://rosettacode.org/wiki/Number_names#Go
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
// Note, for math.MinInt64 this leaves n negative.
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
// work right-to-left
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
|
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)
|
#11l
|
11l
|
F floyd_warshall(n, edge)
V rn = 0 .< n
V dist = rn.map(i -> [1'000'000] * @n)
V nxt = rn.map(i -> [0] * @n)
L(i) rn
dist[i][i] = 0
L(u, v, w) edge
dist[u - 1][v - 1] = w
nxt[u - 1][v - 1] = v - 1
L(k, i, j) cart_product(rn, rn, rn)
V sum_ik_kj = dist[i][k] + dist[k][j]
I dist[i][j] > sum_ik_kj
dist[i][j] = sum_ik_kj
nxt[i][j] = nxt[i][k]
print(‘pair dist path’)
L(i, j) cart_product(rn, rn)
I i != j
V path = [i]
L path.last != j
path.append(nxt[path.last][j])
print(‘#. -> #. #4 #.’.format(i + 1, j + 1, dist[i][j], path.map(p -> String(p + 1)).join(‘ -> ’)))
floyd_warshall(4, [(1, 3, -2), (2, 1, 4), (2, 3, 3), (3, 4, 2), (4, 2, -1)])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.