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
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
PRINT "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.
|
#Elisa
|
Elisa
|
component FormalPowerSeries(Number);
type PowerSeries;
PowerSeries(Size = integer) -> PowerSeries;
+ PowerSeries -> PowerSeries;
- PowerSeries -> PowerSeries;
PowerSeries + PowerSeries -> PowerSeries;
PowerSeries - PowerSeries -> PowerSeries;
PowerSeries * PowerSeries -> PowerSeries;
Integral(PowerSeries) -> PowerSeries;
Differential(PowerSeries) -> PowerSeries;
Zero -> PowerSeries;
One -> PowerSeries;
Array(PowerSeries) -> array(Number);
begin
PowerSeries(Size) = PowerSeries:[T = array(Number, Size); Size];
+ A = A;
- A = [ C = PowerSeries(A.Size);
[ i = 1 .. A.Size; C.T[i] := - A.T[i] ];
C];
A + B = [ if A.Size > B.Size then return(B + A);
C = PowerSeries(B.Size);
[ i = 1 .. A.Size; C.T[i] := A.T[i] + B.T[i] ];
[ i = (A.Size +1) .. B.Size; C.T[i] := B.T[i] ];
C];
A - B = A + (- B );
A * B = [ C = PowerSeries(A.Size + B.Size - 1);
[ i = 1 .. A.Size;
[j = 1.. B.Size;
C.T[i + j - 1] := C.T[i + j - 1] + A.T[i] * B.T[j] ] ];
C];
Integral(A) = [ if A.Size == 0 then return (A);
C = PowerSeries(A.Size + 1);
[ i = 1 .. A.Size; C.T[i +1] := A.T[i] / Number( i )];
C.T[1]:= Number(0);
C ];
Differential(A) = [ if A.Size == 1 then return (A);
C = PowerSeries(A.Size - 1);
[ i = 1 .. C.Size; C.T[i] := A.T[i + 1] * Number( i )];
C ];
Zero = [ C = PowerSeries (1); C.T[1]:= Number(0); C];
One = [ C = PowerSeries (1); C.T[1]:= Number(1); C];
Array(PowerSeries) -> array(Number);
Array(TS) = TS.T;
end component FormalPowerSeries;
|
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.
|
#AWK
|
AWK
|
BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-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.
|
#BaCon
|
BaCon
|
' Formatted numeric output
n = 7.125
PRINT n FORMAT "%09.3f\n"
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands 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).
|
#Action.21
|
Action!
|
DEFINE Bit="BYTE"
TYPE FourBit=[Bit b0,b1,b2,b3]
Bit FUNC Not(Bit a)
RETURN (1-a)
Bit FUNC MyXor(Bit a,b)
RETURN ((Not(a) AND b) OR (a AND Not(b)))
Bit FUNC HalfAdder(Bit a,b Bit POINTER c)
c^=a AND b
RETURN (MyXor(a,b))
Bit FUNC FullAdder(Bit a,b,c0 Bit POINTER c)
Bit s1,c1,s2,c2
s1=HalfAdder(a,c0,@c1)
s2=HalfAdder(b,s1,@c2)
c^=c1 OR c2
RETURN (s2)
PROC FourBitAdder(FourBit POINTER a,b,s Bit POINTER c)
Bit c1,c2,c3
s.b3=FullAdder(a.b3,b.b3,0,@c3)
s.b2=FullAdder(a.b2,b.b2,c3,@c2)
s.b1=FullAdder(a.b1,b.b1,c2,@c1)
s.b0=FullAdder(a.b0,b.b0,c1,c)
RETURN
PROC InitFourBit(BYTE a FourBit POINTER res)
res.b3=a&1 a==RSH 1
res.b2=a&1 a==RSH 1
res.b1=a&1 a==RSH 1
res.b0=a&1
RETURN
PROC PrintFourBit(FourBit POINTER a)
PrintB(a.b0) PrintB(a.b1)
PrintB(a.b2) PrintB(a.b3)
RETURN
PROC Main()
FourBit a,b,s
Bit c
BYTE i,v
FOR i=1 TO 20
DO
v=Rand(16) InitFourBit(v,a)
v=Rand(16) InitFourBit(v,b)
FourBitAdder(a,b,s,@c)
PrintFourBit(a) Print(" + ")
PrintFourBit(b) Print(" = ")
PrintFourBit(s) Print(" Carry=")
PrintBE(c)
OD
RETURN
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#REXX
|
REXX
|
/*REXX pgm finds/shows the number of letters in the Nth word in a constructed sentence*/
@= 'Four is the number of letters in the first word of this sentence,' /*···*/
/* [↑] the start of a long sentence. */
parse arg N M /*obtain optional argument from the CL.*/
if N='' | N="," then N= 201 /*Not specified? Then use the default.*/
if M='' | M="," then M=1000 10000 100000 1000000 /* " " " " " " */
@abcU= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*define the uppercase Latin alphabet. */
!.=.; #.=.; q=1; w=length(N) /* [↓] define some helpful low values.*/
call tell N
if N<0 then say y ' is the length of word ' a " ["word(@, a)"]"
say /* [↑] N negative? Just show 1 number*/
say 'length of sentence= ' length(@) /*display the length of the @ sentence.*/
if M\=='' then do k=1 for words(M) while M\=0 /*maybe handle counts (if specified). */
x=word(M, k) /*obtain the Kth word of the M list. */
call tell -x /*invoke subroutine (with negative arg)*/
say
say y ' is the length of word ' x " ["word(@, x)"]"
say 'length of sentence= ' length(@) /*display length of @ sentence.*/
end /*k*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
wordLen: arg ?; return length(?) - length( space( translate(?, , @abcU), 0) )
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: parse arg z,,$; idx=1; a=abs(z); group=25 /*show 25 numbers per line.*/
/*Q is the last number spelt by $SPELL#*/
do j=1 for a /*traipse through all the numbers to N.*/
do 2 /*perform loop twice (well ··· maybe).*/
y=wordLen( word(@, j) ) /*get the Jth word from the sentence.*/
if y\==0 then leave /*Is the word spelt? Then we're done.*/
q=q + 1 /*bump the on─going (moving) # counter.*/
if #.q==. then #.q=$spell#(q 'Q ORD') /*need to spell A as an ordinal number?*/
_=wordLen( word(@, q) ) /*use the length of the ordinal number.*/
if !._==. then !._=$spell#(_ 'Q') /*Not spelled? Then go and spell it. */
@=@ !._ 'in the' #.q"," /*append words to never─ending sentence*/
end /*2*/ /* [↑] Q ≡ Quiet ORD ≡ ORDinal */
$=$ || right(y, 3) /* [↓] append a justified # to a line.*/
if j//group==0 & z>0 then do; say right(idx, w)'►'$; idx=idx+group; $=; end
end /*j*/ /* [↑] show line if there's enough #s.*/
if $\=='' & z>0 then say right(idx, w)'►'$ /*display if there are residual numbers*/
return
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Pop11
|
Pop11
|
lvars ress;
if sys_fork(false) ->> ress then
;;; parent
printf(ress, 'Child pid = %p\n');
else
printf('In child\n');
endif;
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Python
|
Python
|
import os
pid = os.fork()
if pid > 0:
# parent code
else:
# child code
|
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
|
#Maxima
|
Maxima
|
f(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
|
#MAXScript
|
MAXScript
|
fn multiply a b =
(
a * b
)
|
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
|
#Uniface
|
Uniface
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
// Task: Formal power series type
//
// Go does not have a concept of numeric types other than the built in
// integers, floating points, and so on. Nor does it have function or
// operator overloading, or operator defintion. The type use to implement
// fps here is an interface with a single method, extract.
// While not named in the task description, extract is described in the
// WP article as "important." In fact, by representing a way to index
// all of the coefficients of a fps, any type that implements the interface
// represents a formal power series.
type fps interface {
extract(int) float64
}
// Task: Operations on FPS
//
// Separate operations are implemented with separate extract methods.
// This requires each operation on the fps type to have a concrete type.
// Executing a fps operation is the act of instantiating the concrete type.
// This is implemented here with constructor functions that construct a
// new fps from fps arguments.
// Constructor functions are shown here as a group, followed by concrete
// type definitions and associated extract methods.
func one() fps {
return &oneFps{}
}
func add(s1, s2 fps) fps {
return &sum{s1: s1, s2: s2}
}
func sub(s1, s2 fps) fps {
return &diff{s1: s1, s2: s2}
}
func mul(s1, s2 fps) fps {
return &prod{s1: s1, s2: s2}
}
func div(s1, s2 fps) fps {
return &quo{s1: s1, s2: s2}
}
func differentiate(s1 fps) fps {
return &deriv{s1: s1}
}
func integrate(s1 fps) fps {
return &integ{s1: s1}
}
// Example: Mutually recursive defintion of sine and cosine.
// This is a constructor just as those above. It is nullary and returns
// two fps. Note sin and cos implemented as instances of other fps defined
// above, and so do not need new concrete types. Note also the constant
// term of the integration fps provides the case that terminates recursion
// of the extract function.
func sinCos() (fps, fps) {
sin := &integ{}
cos := sub(one(), integrate(sin))
sin.s1 = cos
return sin, cos
}
// Following are type definitions and extract methods for fps operators
// (constructor functions) just defined.
//
// Goal: lazy evaluation
//
// Go has no built in support for lazy evaluation, so we make it from
// scratch here. Types contain, at a minimum, their fps operands and
// representation neccessary to implement lazy evaluation. Typically
// this is a coefficient slice, although constant terms are not stored,
// so in the case of a constant fps, no slice is needed at all.
// Coefficients are generated only as they are requested. Computed
// coefficients are stored in the slice and if requested subsequently,
// are returned immediately rather than recomputed.
//
// Types can also contain any other intermediate values useful for
// computing coefficients.
// Constant one: A constant is a nullary function and no coefficent
// storage is needed so an empty struct is used for the type.
type oneFps struct{}
// The extract method implements the fps interface. It simply has to
// return 1 for the first term and return 0 for all other terms.
func (*oneFps) extract(n int) float64 {
if n == 0 {
return 1
}
return 0
}
// Addition is a binary function so the sum type stores its two fps operands
// and its computed terms.
type sum struct {
s []float64
s1, s2 fps
}
func (s *sum) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))
}
return s.s[n]
}
// Subtraction and other binary operations are similar.
// (The common field definitions could be factored out with an embedded
// struct, but the clutter of the extra syntax required doesn't seem
// to be worthwhile.)
type diff struct {
s []float64
s1, s2 fps
}
func (s *diff) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))
}
return s.s[n]
}
type prod struct {
s []float64
s1, s2 fps
}
func (s *prod) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
c := 0.
for k := 0; k <= i; k++ {
c += s.s1.extract(k) * s.s1.extract(n-k)
}
s.s = append(s.s, c)
}
return s.s[n]
}
// Note a couple of fields in addition to those of other binary operators.
// They simply optimize computations a bit.
type quo struct {
s1, s2 fps
inv float64 // optimizes a divide
c []float64 // saves multiplications
s []float64
}
// WP formula. Note the limitation s2[0] cannot be 0. In this case
// the function returns NaN for all terms. The switch statement catches
// this case and avoids storing a slice of all NaNs.
func (s *quo) extract(n int) float64 {
switch {
case len(s.s) > 0:
case !math.IsInf(s.inv, 1):
a0 := s.s2.extract(0)
s.inv = 1 / a0
if a0 != 0 {
break
}
fallthrough
default:
return math.NaN()
}
for i := len(s.s); i <= n; i++ {
c := 0.
for k := 1; k <= i; k++ {
c += s.s2.extract(k) * s.c[n-k]
}
c = s.s1.extract(i) - c*s.inv
s.c = append(s.c, c)
s.s = append(s.s, c*s.inv)
}
return s.s[n]
}
// Note differentiation and integration are unary so their types contain
// only a single fps operand.
type deriv struct {
s []float64
s1 fps
}
func (s *deriv) extract(n int) float64 {
for i := len(s.s); i <= n; {
i++
s.s = append(s.s, float64(i)*s.s1.extract(i))
}
return s.s[n]
}
type integ struct {
s []float64
s1 fps
}
func (s *integ) extract(n int) float64 {
if n == 0 {
return 0 // constant term C=0
}
// with constant term handled, s starts at 1
for i := len(s.s) + 1; i <= n; i++ {
s.s = append(s.s, s.s1.extract(i-1)/float64(i))
}
return s.s[n-1]
}
// Demonstrate working sin, cos.
func main() {
// Format several terms in a way that is easy to compare visually.
partialSeries := func(f fps) (s string) {
for i := 0; i < 6; i++ {
s = fmt.Sprintf("%s %8.5f ", s, f.extract(i))
}
return
}
sin, cos := sinCos()
fmt.Println("sin:", partialSeries(sin))
fmt.Println("cos:", partialSeries(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.
|
#BBC_BASIC
|
BBC BASIC
|
PRINT FNformat(PI, 9, 3)
PRINT FNformat(-PI, 9, 3)
END
DEF FNformat(n, sl%, dp%)
LOCAL @%
@% = &1020000 OR dp% << 8
IF n >= 0 THEN
= RIGHT$(STRING$(sl%,"0") + STR$(n), sl%)
ENDIF
= "-" + RIGHT$(STRING$(sl%,"0") + STR$(-n), sl%-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.
|
#bc
|
bc
|
/*
* Print number n, using at least c characters.
*
* Different from normal, this function:
* 1. Uses the current ibase (not the obase) to print the number.
* 2. Prunes "0" digits from the right, so p(1.500, 1) prints "1.5".
* 3. Pads "0" digits to the left, so p(-1.5, 6) prints "-001.5".
* 4. Never prints a newline.
*
* Use an assignment, as t = p(1.5, 1), to discard the return value
* from this function so that bc not prints the return value.
*/
define p(n, c) {
auto d, d[], f, f[], i, m, r, s, v
s = scale /* Save original scale. */
if (n < 0) {
"-" /* Print negative sign. */
c -= 1
n = -n /* Remove negative sign from n. */
}
/* d[] takes digits before the radix point. */
scale = 0
for (m = n / 1; m != 0; m /= 10) d[d++] = m % 10
/* f[] takes digits after the radix point. */
r = n - (n / 1) /* r is these digits. */
scale = scale(n)
f = -1 /* f counts the digits of r. */
for (m = r + 1; m != 0; m /= 10) f += 1
scale = 0
r = r * (10 ^ f) / 1 /* Remove radix point from r. */
if (r != 0) {
while (r % 10 == 0) { /* Prune digits. */
f -= 1
r /= 10
}
for (i = 0; i < f; i++) {
f[i] = r % 10
r /= 10
}
}
/* Pad "0" digits to reach c characters. */
c -= d
if (f > 0) c -= 1 + f
for (1; c > 0; c--) "0" /* Print "0". */
/* i = index, m = maximum index, r = digit to print. */
m = d + f
for (i = 1; i <= m; i++) {
if (i <= d) r = d[d - i]
if (i > d) r = f[m - i]
if (i == d + 1) "." /* Print radix point. */
v = 0
if (r == v++) "0" /* Print digit. */
if (r == v++) "1"
if (r == v++) "2" /* r == 2 might not work, */
if (r == v++) "3" /* unless ibase is ten. */
if (r == v++) "4"
if (r == v++) "5"
if (r == v++) "6"
if (r == v++) "7"
if (r == v++) "8"
if (r == v++) "9"
if (r == v++) "A"
if (r == v++) "B"
if (r == v++) "C"
if (r == v++) "D"
if (r == v++) "E"
if (r == v++) "F"
}
scale = s /* Restore original scale. */
}
|
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).
|
#Ada
|
Ada
|
type Four_Bits is array (1..4) of Boolean;
procedure Half_Adder (Input_1, Input_2 : Boolean; Output, Carry : out Boolean) is
begin
Output := Input_1 xor Input_2;
Carry := Input_1 and Input_2;
end Half_Adder;
procedure Full_Adder (Input_1, Input_2 : Boolean; Output : out Boolean; Carry : in out Boolean) is
T_1, T_2, T_3 : Boolean;
begin
Half_Adder (Input_1, Input_2, T_1, T_2);
Half_Adder (Carry, T_1, Output, T_3);
Carry := T_2 or T_3;
end Full_Adder;
procedure Four_Bits_Adder (A, B : Four_Bits; C : out Four_Bits; Carry : in out Boolean) is
begin
Full_Adder (A (4), B (4), C (4), Carry);
Full_Adder (A (3), B (3), C (3), Carry);
Full_Adder (A (2), B (2), C (2), Carry);
Full_Adder (A (1), B (1), C (1), Carry);
end Four_Bits_Adder;
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Rust
|
Rust
|
struct NumberNames {
cardinal: &'static str,
ordinal: &'static str,
}
impl NumberNames {
fn get_name(&self, ordinal: bool) -> &'static str {
if ordinal {
return self.ordinal;
}
self.cardinal
}
}
const SMALL_NAMES: [NumberNames; 20] = [
NumberNames {
cardinal: "zero",
ordinal: "zeroth",
},
NumberNames {
cardinal: "one",
ordinal: "first",
},
NumberNames {
cardinal: "two",
ordinal: "second",
},
NumberNames {
cardinal: "three",
ordinal: "third",
},
NumberNames {
cardinal: "four",
ordinal: "fourth",
},
NumberNames {
cardinal: "five",
ordinal: "fifth",
},
NumberNames {
cardinal: "six",
ordinal: "sixth",
},
NumberNames {
cardinal: "seven",
ordinal: "seventh",
},
NumberNames {
cardinal: "eight",
ordinal: "eighth",
},
NumberNames {
cardinal: "nine",
ordinal: "ninth",
},
NumberNames {
cardinal: "ten",
ordinal: "tenth",
},
NumberNames {
cardinal: "eleven",
ordinal: "eleventh",
},
NumberNames {
cardinal: "twelve",
ordinal: "twelfth",
},
NumberNames {
cardinal: "thirteen",
ordinal: "thirteenth",
},
NumberNames {
cardinal: "fourteen",
ordinal: "fourteenth",
},
NumberNames {
cardinal: "fifteen",
ordinal: "fifteenth",
},
NumberNames {
cardinal: "sixteen",
ordinal: "sixteenth",
},
NumberNames {
cardinal: "seventeen",
ordinal: "seventeenth",
},
NumberNames {
cardinal: "eighteen",
ordinal: "eighteenth",
},
NumberNames {
cardinal: "nineteen",
ordinal: "nineteenth",
},
];
const TENS: [NumberNames; 8] = [
NumberNames {
cardinal: "twenty",
ordinal: "twentieth",
},
NumberNames {
cardinal: "thirty",
ordinal: "thirtieth",
},
NumberNames {
cardinal: "forty",
ordinal: "fortieth",
},
NumberNames {
cardinal: "fifty",
ordinal: "fiftieth",
},
NumberNames {
cardinal: "sixty",
ordinal: "sixtieth",
},
NumberNames {
cardinal: "seventy",
ordinal: "seventieth",
},
NumberNames {
cardinal: "eighty",
ordinal: "eightieth",
},
NumberNames {
cardinal: "ninety",
ordinal: "ninetieth",
},
];
struct NamedNumber {
cardinal: &'static str,
ordinal: &'static str,
number: usize,
}
impl NamedNumber {
fn get_name(&self, ordinal: bool) -> &'static str {
if ordinal {
return self.ordinal;
}
self.cardinal
}
}
const N: usize = 7;
const NAMED_NUMBERS: [NamedNumber; N] = [
NamedNumber {
cardinal: "hundred",
ordinal: "hundredth",
number: 100,
},
NamedNumber {
cardinal: "thousand",
ordinal: "thousandth",
number: 1000,
},
NamedNumber {
cardinal: "million",
ordinal: "millionth",
number: 1000000,
},
NamedNumber {
cardinal: "billion",
ordinal: "billionth",
number: 1000000000,
},
NamedNumber {
cardinal: "trillion",
ordinal: "trillionth",
number: 1000000000000,
},
NamedNumber {
cardinal: "quadrillion",
ordinal: "quadrillionth",
number: 1000000000000000,
},
NamedNumber {
cardinal: "quintillion",
ordinal: "quintillionth",
number: 1000000000000000000,
},
];
fn big_name(n: usize) -> &'static NamedNumber {
for i in 1..N {
if n < NAMED_NUMBERS[i].number {
return &NAMED_NUMBERS[i - 1];
}
}
&NAMED_NUMBERS[N - 1]
}
fn count_letters(s: &str) -> usize {
let mut count = 0;
for c in s.chars() {
if c.is_alphabetic() {
count += 1;
}
}
count
}
struct WordList {
words: Vec<(usize, usize)>,
string: String,
}
impl WordList {
fn new() -> WordList {
WordList {
words: Vec::new(),
string: String::new(),
}
}
fn append(&mut self, s: &str) {
let offset = self.string.len();
self.string.push_str(s);
self.words.push((offset, offset + s.len()));
}
fn extend(&mut self, s: &str) {
let len = self.words.len();
let mut w = &mut self.words[len - 1];
w.1 += s.len();
self.string.push_str(s);
}
fn len(&self) -> usize {
self.words.len()
}
fn sentence_length(&self) -> usize {
let n = self.words.len();
if n == 0 {
return 0;
}
self.string.len() + n - 1
}
fn get_word(&self, index: usize) -> &str {
let w = &self.words[index];
&self.string[w.0..w.1]
}
}
fn append_number_name(words: &mut WordList, n: usize, ordinal: bool) -> usize {
let mut count = 0;
if n < 20 {
words.append(SMALL_NAMES[n].get_name(ordinal));
count += 1;
} else if n < 100 {
if n % 10 == 0 {
words.append(TENS[n / 10 - 2].get_name(ordinal));
} else {
words.append(TENS[n / 10 - 2].get_name(false));
words.extend("-");
words.extend(SMALL_NAMES[n % 10].get_name(ordinal));
}
count += 1;
} else {
let big = big_name(n);
count += append_number_name(words, n / big.number, false);
if n % big.number == 0 {
words.append(big.get_name(ordinal));
count += 1;
} else {
words.append(big.get_name(false));
count += 1;
count += append_number_name(words, n % big.number, ordinal);
}
}
count
}
fn sentence(count: usize) -> WordList {
let mut result = WordList::new();
const WORDS: &'static [&'static str] = &[
"Four",
"is",
"the",
"number",
"of",
"letters",
"in",
"the",
"first",
"word",
"of",
"this",
"sentence,",
];
for s in WORDS {
result.append(s);
}
let mut n = result.len();
let mut i = 1;
while count > n {
let count = count_letters(result.get_word(i));
n += append_number_name(&mut result, count, false);
result.append("in");
result.append("the");
n += 2;
n += append_number_name(&mut result, i + 1, true);
result.extend(",");
i += 1;
}
result
}
fn main() {
let mut n = 201;
let s = sentence(n);
println!("Number of letters in first {} words in the sequence:", n);
for i in 0..n {
if i != 0 {
if i % 25 == 0 {
println!();
} else {
print!(" ");
}
}
print!("{:2}", count_letters(s.get_word(i)));
}
println!();
println!("Sentence length: {}", s.sentence_length());
n = 1000;
while n <= 10000000 {
let s = sentence(n);
let word = s.get_word(n - 1);
print!(
"The {}th word is '{}' and has {} letters. ",
n,
word,
count_letters(word)
);
println!("Sentence length: {}", s.sentence_length());
n *= 10;
}
}
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#Wren
|
Wren
|
import "/fmt" for Fmt
var names = {
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"
}
var bigNames = {
1e3 : "thousand",
1e6 : "million",
1e9 : "billion",
1e12: "trillion",
1e15: "quadrillion"
}
var irregOrdinals = {
"one" : "first",
"two" : "second",
"three" : "third",
"five" : "fifth",
"eight" : "eighth",
"nine" : "ninth",
"twelve": "twelfth"
}
var strToOrd = Fn.new { |s|
if (s == "zero") return "zeroth" // or alternatively 'zeroeth'
var splits = s.replace("-", " ").split(" ")
var last = splits[-1]
return irregOrdinals.containsKey(last) ? s[0...-last.count] + irregOrdinals[last] :
last.endsWith("y") ? s[0...-1] + "ieth" : s + "th"
}
var numToText = Fn.new { |n, uk|
if (n == 0) return "zero"
var neg = n < 0
var nn = neg ? - n : n
var digits3 = List.filled(6, 0)
for (i in 0..5) { // split number into groups of 3 digits from the right
digits3[i] = nn % 1000
nn = (nn / 1000).truncate
}
var threeDigitsToText = Fn.new { |number|
var sb = ""
if (number == 0) return ""
var hundreds = (number / 100).truncate
var remainder = number % 100
if (hundreds > 0) {
sb = sb + names[hundreds] + " hundred"
if (remainder > 0) sb = sb + (uk ? " and " : " ")
}
if (remainder > 0) {
var tens = (remainder / 10).truncate
var units = remainder % 10
if (tens > 1) {
sb = sb + names[tens * 10]
if (units > 0) sb = sb + "-" + names[units]
} else {
sb = sb + names[remainder]
}
}
return sb
}
var strings = List.filled(6, 0)
for (i in 0..5) strings[i] = threeDigitsToText.call(digits3[i])
var text = strings[0]
var andNeeded = uk && 1 <= digits3[0] && digits3[0] <= 99
var big = 1000
for (i in 1..5) {
if (digits3[i] > 0) {
var text2 = strings[i] + " " + bigNames[big]
if (!text.isEmpty) {
text2 = text2 + (andNeeded ? " and " : " ") // no commas inserted in this version
andNeeded = false
} else {
andNeeded = uk && 1 <= digits3[i] && digits3[i] <= 99
}
text = text2 + text
}
big = big * 1000
}
if (neg) text = "minus " + text
return text
}
var opening = "Four is the number of letters in the first word of this sentence,".split(" ")
var adjustedLength = Fn.new { |s| s.replace(",", "").replace("-", "").count } // no ',' or '-'
var getWords = Fn.new { |n|
var words = []
words.addAll(opening)
if (n > opening.count) {
var k = 2
while (true) {
var len = adjustedLength.call(words[k - 1])
var text = numToText.call(len, false)
var splits = text.split(" ")
words.addAll(splits)
words.add("in")
words.add("the")
var text2 = strToOrd.call(numToText.call(k, false)) + "," // add trailing comma
var splits2 = text2.split(" ")
words.addAll(splits2)
if (words.count >= n) break
k = k + 1
}
}
return words
}
var getLengths = Fn.new { |n|
var words = getWords.call(n)
var lengths = words.take(n).map { |w| adjustedLength.call(w) }.toList
// includes hyphens, commas & spaces
var sentenceLength = words.reduce(0) { |acc, w| acc + w.count } + words.count - 1
return [lengths, sentenceLength]
}
var getLastWord = Fn.new { |n|
var words = getWords.call(n)
var nthWord = words[n - 1]
var nthWordLength = adjustedLength.call(nthWord)
// includes hyphens, commas & spaces
var sentenceLength = words.reduce(0) { |acc, w| acc + w.count } + words.count - 1
return [nthWord, nthWordLength, sentenceLength]
}
var n = 201
System.print("The lengths of the first %(n) words are:\n")
var res = getLengths.call(n)
var list = res[0]
var sentenceLength = res[1]
for (i in 0...n) {
if (i % 25 == 0) {
if (i > 0) System.print()
Fmt.write("$3d: ", i + 1)
}
Fmt.write("$3d", list[i])
}
Fmt.print("\n\nLength of sentence = $,d\n", sentenceLength)
n = 1000
while (true) {
var res = getLastWord.call(n)
var word = res[0]
var wLen = res[1]
var sLen = res[2]
if (word.endsWith(",")) word = word[0...-1] // strip off any trailing comma
Fmt.print("The length of word $,d [$s] is $d", n, word, wLen)
Fmt.print("Length of sentence = $,d\n", sLen)
n = n * 10
if (n > 1e7) break
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#R
|
R
|
p <- parallel::mcparallel({
Sys.sleep(1)
cat("\tChild pid: ", Sys.getpid(), "\n")
TRUE
})
cat("Main pid: ", Sys.getpid(), "\n")
parallel::mccollect(p)
p <- parallel:::mcfork()
if (inherits(p, "masterProcess")) {
Sys.sleep(1)
cat("\tChild pid: ", Sys.getpid(), "\n")
parallel:::mcexit(, TRUE)
}
cat("Main pid: ", Sys.getpid(), "\n")
unserialize(parallel:::readChildren(2))
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Racket
|
Racket
|
#lang racket
(define-values [P _out _in _err]
(subprocess (current-output-port) (current-input-port) (current-error-port)
(find-executable-path "du") "-hs" "/usr/share"))
;; wait for process to end, print messages as long as it runs
(let loop () (unless (sync/timeout 10 P) (printf "Still running...\n") (loop)))
|
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
|
#Mercury
|
Mercury
|
% Module ceremony elided...
:- func multiply(integer, integer) = integer.
multiply(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
|
#Metafont
|
Metafont
|
primarydef a mult b = a * b enddef;
|
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
|
#Unison
|
Unison
|
main = '(printLine "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.
|
#Haskell
|
Haskell
|
newtype Series a = S { coeffs :: [a] } deriving (Eq, Show)
-- Invariant: coeffs must be an infinite list
instance Num a => Num (Series a) where
fromInteger n = S $ fromInteger n : repeat 0
negate (S fs) = S $ map negate fs
S fs + S gs = S $ zipWith (+) fs gs
S (f:ft) * S gs@(g:gt) = S $ f*g : coeffs (S ft * S gs + S (map (f*) gt))
instance Fractional a => Fractional (Series a) where
fromRational n = S $ fromRational n : repeat 0
S (f:ft) / S (g:gt) = S qs where qs = f/g : map (/g) (coeffs (S ft - S qs * S gt))
-- utility function to convert from a finite polynomial
fromFiniteList xs = S (xs ++ repeat 0)
int (S fs) = S $ 0 : zipWith (/) fs [1..]
diff (S (_:ft)) = S $ zipWith (*) ft [1..]
sinx,cosx :: Series Rational
sinx = int cosx
cosx = 1 - int sinx
fiboS = 1 / fromFiniteList [1,-1,-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.
|
#Beads
|
Beads
|
beads 1 program 'Formatted numeric output'
calc main_init
var num = 7.125
log to_str(num, min:9, zero_pad:Y)
|
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.
|
#C
|
C
|
#include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 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).
|
#AutoHotkey
|
AutoHotkey
|
A := 13
B := 9
N := FourBitAdd(A, B)
MsgBox, % A " + " B ":`n"
. GetBin4(A) " + " GetBin4(B) " = " N.S " (Carry = " N.C ")"
return
Xor(A, B) {
return (~A & B) | (A & ~B)
}
HalfAdd(A, B) {
return {"S": Xor(A, B), "C": A & B}
}
FullAdd(A, B, C=0) {
X := HalfAdd(A, C)
Y := HalfAdd(B, X.S)
return {"S": Y.S, "C": X.C | Y.C}
}
FourBitAdd(A, B, C=0) {
A := GetFourBits(A)
B := GetFourBits(B)
X := FullAdd(A[4], B[4], C)
Y := FullAdd(A[3], B[3], X.C)
W := FullAdd(A[2], B[2], Y.C)
Z := FullAdd(A[1], B[1], W.C)
return {"S": Z.S W.S Y.S X.S, "C": Z.C}
}
GetFourBits(N) {
if (N < 0 || N > 15)
return -1
return StrSplit(GetBin4(N))
}
GetBin4(N) {
Loop 4
Res := Mod(N, 2) Res, N := N >> 1
return, Res
}
|
http://rosettacode.org/wiki/Four_is_the_number_of_letters_in_the_...
|
Four is the number of letters in the ...
|
The Four is ... sequence is based on the counting of the number of
letters in the words of the (never─ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ···
Definitions and directives
English is to be used in spelling numbers.
Letters are defined as the upper─ and lowercase letters in the Latin alphabet (A──►Z and a──►z).
Commas are not counted, nor are hyphens (dashes or minus signs).
twenty─three has eleven letters.
twenty─three is considered one word (which is hyphenated).
no and words are to be used when spelling a (English) word for a number.
The American version of numbers will be used here in this task (as opposed to the British version).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first N words in the never─ending sentence. For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
4 2 3 6 2 7
Only construct as much as is needed for the never─ending sentence.
Write a driver (invoking routine) to show the number of letters in the Nth word, as well as showing the Nth word itself.
After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
Show all output here.
Test cases
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
Related tasks
Four is magic
Look-and-say sequence
Number names
Self-describing numbers
Self-referential sequence
Spelling of ordinal numbers
Also see
See the OEIS sequence A72425 "Four is the number of letters...".
See the OEIS sequence A72424 "Five's the number of letters..."
|
#zkl
|
zkl
|
// Built the sentence in little chucks but only save the last one
// Save the word counts
fcn fourIsThe(text,numWords){
const rmc="-,";
seq:=(text - rmc).split().apply("len").copy(); // (4,2,3,6...)
szs:=Data(numWords + 100,Int).howza(0).extend(seq); // bytes
cnt,lastWords := seq.len(),"";
total:=seed.len() - 1; // don't count trailing space
foreach idx in ([1..]){
sz:=szs[idx];
a,b := nth(sz,False),nth(idx+1); // "two","three hundred sixty-seventh"
lastWords="%s in the %s, ".fmt(a,b);
ws:=lastWords.counts(" ")[1]; // "five in the forty-ninth " --> 4
cnt+=ws; total+=lastWords.len();
lastWords.split().pump(szs.append,'-(rmc),"len");
if(cnt>=numWords){
if(cnt>numWords){
z,n:=lastWords.len(),z-2;
do(cnt - numWords){ n=lastWords.rfind(" ",n) - 1; }
lastWords=lastWords[0,n+1]; total-=(z - n);
}
break;
}
}
return(lastWords.strip(),szs,total);
}
fcn lastWord(sentence){ sentence[sentence.rfind(" ")+1,*] }
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Raku
|
Raku
|
use NativeCall;
sub fork() returns int32 is native { ... }
if fork() -> $pid {
print "I am the proud parent of $pid.\n";
}
else {
print "I am a child. Have you seen my mommy?\n";
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#REXX
|
REXX
|
child = fork()
|
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
|
#min
|
min
|
'* :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
|
#MiniScript
|
MiniScript
|
multiply = function(x,y)
return x*y
end function
print multiply(6, 7)
|
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.)
|
#11l
|
11l
|
V dif = s -> enumerate(s[1..]).map2((i, x) -> x - @s[i])
F difn(s, n) -> [Int]
R I n != 0 {difn(dif(s), n - 1)} E s
V s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
L(i) 10
print(difn(s, i))
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/sh
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.
|
#J
|
J
|
Ai=: (i.@] =/ i.@[ -/ i.@>:@-)&#
divide=: [ +/ .*~ [:%.&.x: ] +/ .* Ai
diff=: 1 }. ] * i.@#
intg=: 0 , ] % 1 + i.@#
mult=: +//.@(*/)
plus=: +/@,:
minus=: -/@,:
|
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.
|
#C.23
|
C#
|
class Program
{
static void Main(string[] args)
{
float myNumbers = 7.125F;
string strnumber = Convert.ToString(myNumbers);
Console.WriteLine(strnumber.PadLeft(9, '0'));
Console.ReadLine();
}
}
|
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.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('0') << std::setw(9) << std::fixed << std::setprecision(3) << 7.125 << std::endl;
return 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).
|
#AutoIt
|
AutoIt
|
Func _NOT($_A)
Return (Not $_A) *1
EndFunc ;==>_NOT
Func _AND($_A, $_B)
Return BitAND($_A, $_B)
EndFunc ;==>_AND
Func _OR($_A, $_B)
Return BitOR($_A, $_B)
EndFunc ;==>_OR
Func _XOR($_A, $_B)
Return _OR( _
_AND( $_A, _NOT($_B) ), _
_AND( _NOT($_A), $_B) )
EndFunc ;==>_XOR
Func _HalfAdder($_A, $_B, ByRef $_CO)
$_CO = _AND($_A, $_B)
Return _XOR($_A, $_B)
EndFunc ;==>_HalfAdder
Func _FullAdder($_A, $_B, $_CI, ByRef $_CO)
Local $CO1, $CO2, $Q1, $Q2
$Q1 = _HalfAdder($_A, $_B, $CO1)
$Q2 = _HalfAdder($Q1, $_CI, $CO2)
$_CO = _OR($CO2, $CO1)
Return $Q2
EndFunc ;==>_FullAdder
Func _4BitAdder($_A1, $_A2, $_A3, $_A4, $_B1, $_B2, $_B3, $_B4, $_CI, ByRef $_CO)
Local $CO1, $CO2, $CO3, $CO4, $Q1, $Q2, $Q3, $Q4
$Q1 = _FullAdder($_A4, $_B4, $_CI, $CO1)
$Q2 = _FullAdder($_A3, $_B3, $CO1, $CO2)
$Q3 = _FullAdder($_A2, $_B2, $CO2, $CO3)
$Q4 = _FullAdder($_A1, $_B1, $CO3, $CO4)
$_CO = $CO4
Return $Q4 & $Q3 & $Q2 & $Q1
EndFunc ;==>_4BitAdder
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Ruby
|
Ruby
|
pid = fork
if pid
# parent code
else
# child code
end
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Run_BASIC
|
Run BASIC
|
run "someProgram.bas",#handle
render #handle ' this runs the program until it waits
' both the parent and child are running
' --------------------------------------------------------
' You can also call a function in the someProgram.bas program.
' For example if it had a DisplayBanner Funciton.
#handle DisplayBanner("Welcome!")
|
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
|
#MiniZinc
|
MiniZinc
|
function var int:multiply(a: var int,b: var int) =
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
|
#.D0.9C.D0.9A-61.2F52
|
МК-61/52
|
ИП0 ИП1 * В/О
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#Ada
|
Ada
|
with Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.containers.Vectors;
procedure Forward_Difference is
package Flt_Vect is new Ada.Containers.Vectors(Positive, Float);
use Flt_Vect;
procedure Print(Item : Vector) is
begin
if not Item.Is_Empty then
Ada.Text_IO.Put('[');
for I in 1..Item.Length loop
Put(Item => Item.Element(Positive(I)), Fore => 1, Aft => 1, Exp => 0);
if Positive(I) < Positive(Item.Length) then
Ada.Text_Io.Put(", ");
end if;
end loop;
Ada.Text_Io.Put_line("]");
else
Ada.Text_IO.Put_Line("Empty List");
end if;
end Print;
function Diff(Item : Vector; Num_Passes : Natural) return Vector is
A : Vector := Item;
B : Vector := Empty_Vector;
begin
if not A.Is_Empty then
for I in 1..Num_Passes loop
for I in 1..Natural(A.Length) - 1 loop
B.Append(A.Element(I + 1) - A.Element(I));
end loop;
Move(Target => A, Source => B);
end loop;
end if;
return A;
end Diff;
Values : array(1..10) of Float := (90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0);
A : Vector;
begin
for I in Values'range loop
A.Append(Values(I)); -- Fill the vector
end loop;
Print(Diff(A, 1));
Print(Diff(A, 2));
Print(Diff(A, 9));
Print(Diff(A, 10));
print(Diff(A, 0));
end Forward_Difference;
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Unlambda
|
Unlambda
|
`r```````````````.G.o.o.d.b.y.e.,. .W.o.r.l.d.!i
|
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.
|
#Java
|
Java
|
1/(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.
|
#Clojure
|
Clojure
|
(cl-format true "~9,3,,,'0F" 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.
|
#COBOL
|
COBOL
|
IDENTIFICATION DIVISION.
PROGRAM-ID. NUMERIC-OUTPUT-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-EXAMPLE.
05 X PIC 9(5)V9(3).
PROCEDURE DIVISION.
MOVE 7.125 TO X.
DISPLAY X UPON CONSOLE.
STOP RUN.
|
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).
|
#BASIC
|
BASIC
|
100 S$ = "1100 + 1100 = " : GOSUB 400
110 S$ = "1100 + 1101 = " : GOSUB 400
120 S$ = "1100 + 1110 = " : GOSUB 400
130 S$ = "1100 + 1111 = " : GOSUB 400
140 S$ = "1101 + 0000 = " : GOSUB 400
150 S$ = "1101 + 0001 = " : GOSUB 400
160 S$ = "1101 + 0010 = " : GOSUB 400
170 S$ = "1101 + 0011 = " : GOSUB 400
180 END
400 A0 = VAL(MID$(S$, 4, 1))
410 A1 = VAL(MID$(S$, 3, 1))
420 A2 = VAL(MID$(S$, 2, 1))
430 A3 = VAL(MID$(S$, 1, 1))
440 B0 = VAL(MID$(S$, 11, 1))
450 B1 = VAL(MID$(S$, 10, 1))
460 B2 = VAL(MID$(S$, 9, 1))
470 B3 = VAL(MID$(S$, 8, 1))
480 GOSUB 600
490 PRINT S$;
REM 4 BIT PRINT
500 PRINT C;S3;S2;S1;S0
510 RETURN
REM 4 BIT ADD
REM ADD A3 A2 A1 A0 TO B3 B2 B1 B0
REM RESULT IN S3 S2 S1 S0
REM CARRY IN C
600 C = 0
610 A = A0 : B = B0 : GOSUB 700 : S0 = S
620 A = A1 : B = B1 : GOSUB 700 : S1 = S
630 A = A2 : B = B2 : GOSUB 700 : S2 = S
640 A = A3 : B = B3 : GOSUB 700 : S3 = S
650 RETURN
REM FULL ADDER
REM ADD A + B + C
REM RESULT IN S
REM CARRY IN C
700 BH = B : B = C : GOSUB 800 : C1 = C
710 A = S : B = BH : GOSUB 800 : C2 = C
720 C = C1 OR C2
730 RETURN
REM HALF ADDER
REM ADD A + B
REM RESULT IN S
REM CARRY IN C
800 GOSUB 900 : S = C
810 C = A AND B
820 RETURN
REM XOR GATE
REM A XOR B
REM RESULT IN C
900 C = A AND NOT B
910 D = B AND NOT A
920 C = C OR D
930 RETURN
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Rust
|
Rust
|
use nix::unistd::{fork, ForkResult};
use std::process::id;
fn main() {
match fork() {
Ok(ForkResult::Parent { child, .. }) => {
println!(
"This is the original process(pid: {}). New child has pid: {}",
id(),
child
);
}
Ok(ForkResult::Child) => println!("This is the new process(pid: {}).", id()),
Err(_) => println!("Something went wrong."),
}
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Scala
|
Scala
|
import java.io.IOException
object Fork extends App {
val builder: ProcessBuilder = new ProcessBuilder()
val currentUser: String = builder.environment.get("USER")
val command: java.util.List[String] = java.util.Arrays.asList("ps", "-f", "-U", currentUser)
builder.command(command)
try {
val lines = scala.io.Source.fromInputStream(builder.start.getInputStream).getLines()
println(s"Output of running $command is:")
while (lines.hasNext) println(lines.next())
}
catch {
case iox: IOException => iox.printStackTrace()
}
}
|
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
|
#Modula-2
|
Modula-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.)
|
#ALGOL_68
|
ALGOL 68
|
main:(
MODE LISTREAL = [1:0]REAL;
OP - = (LISTREAL a,b)LISTREAL: (
[UPB a]REAL out;
FOR i TO UPB out DO out[i]:=a[i]-b[i] OD;
out
);
FORMAT real fmt=$zzz-d.d$;
FORMAT repeat fmt = $n(UPB s-1)(f(real fmt)",")f(real fmt)$;
FORMAT list fmt = $"("f(UPB s=1|real fmt|repeat fmt)")"$;
FLEX [1:0] REAL s := (90, 47, 58, 29, 22, 32, 55, 5, 55, 73);
printf((list fmt,s,$";"l$));
TO UPB s-1 DO
s := s[2:] - s[:UPB s-1];
printf((list fmt,s,$";"l$))
OD
)
|
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
|
#Ursa
|
Ursa
|
out "hello world!" endl console
|
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.
|
#jq
|
jq
|
1/(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.
|
#Common_Lisp
|
Common Lisp
|
(format t "~9,3,,,'0F" 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.
|
#D
|
D
|
import std.stdio;
void main() {
immutable r = 7.125;
writefln(" %9.3f", -r);
writefln(" %9.3f", r);
writefln(" %-9.3f", r);
writefln(" %09.3f", -r);
writefln(" %09.3f", r);
writefln(" %-09.3f", r);
}
|
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).
|
#Batch_File
|
Batch File
|
@echo off
setlocal enabledelayedexpansion
:: ":main" is where all the non-logic-gate stuff happens
:main
:: User input two 4-digit binary numbers
:: There is no error checking for these numbers, however if the first 4 digits of both inputs are in binary...
:: The program will use them. All non-binary numbers are treated as 0s, but having less than 4 digits will crash it
set /p "input1=First 4-Bit Binary Number: "
set /p "input2=Second 4-Bit Binary Number: "
:: Put the first 4 digits of the binary numbers and separate them into "A[]" for input A and "B[]" for input B
for /l %%i in (0,1,3) do (
set A%%i=!input1:~%%i,1!
set B%%i=!input2:~%%i,1!
)
:: Run the 4-bit Adder with "A[]" and "B[]" as parameters. The program supports a 9th parameter for a Carry input
call:_4bitAdder %A3% %A2% %A1% %A0% %B3% %B2% %B1% %B0% 0
:: Display the answer and exit
echo %input1% + %input2% = %outputC%%outputS4%%outputS3%%outputS2%%outputS1%
pause>nul
exit /b
:: Function for the 4-bit Adder following the logic given
:_4bitAdder
set inputA1=%1
set inputA2=%2
set inputA3=%3
set inputA4=%4
set inputB1=%5
set inputB2=%6
set inputB3=%7
set inputB4=%8
set inputC=%9
call:_FullAdder %inputA1% %inputB1% %inputC%
set outputS1=%outputS%
set inputC=%outputC%
call:_FullAdder %inputA2% %inputB2% %inputC%
set outputS2=%outputS%
set inputC=%outputC%
call:_FullAdder %inputA3% %inputB3% %inputC%
set outputS3=%outputS%
set inputC=%outputC%
call:_FullAdder %inputA4% %inputB4% %inputC%
set outputS4=%outputS%
set inputC=%outputC%
:: In order return more than one number (of which is usually done via 'exit /b') we declare them while ending the local environment
endlocal && set "outputS1=%outputS1%" && set "outputS2=%outputS2%" && set "outputS3=%outputS3%" && set "outputS4=%outputS4%" && set "outputC=%inputC%"
exit /b
:: Function for the 1-bit Adder following the logic given
:_FullAdder
setlocal
set inputA=%1
set inputB=%2
set inputC1=%3
call:_halfAdder %inputA% %inputB%
set inputA1=%outputS%
set inputA2=%inputA1%
set inputC2=%outputC%
call:_HalfAdder %inputA1% %inputC1%
set outputS=%outputS%
set inputC1=%outputC%
call:_Or %inputC1% %inputC2%
set outputC=%errorlevel%
endlocal && set "outputS=%outputS%" && set "outputC=%outputC%"
exit /b
:: Function for the half-bit adder following the logic given
:_halfAdder
setlocal
set inputA1=%1
set inputA2=%inputA1%
set inputB1=%2
set inputB2=%inputB1%
call:_XOr %inputA1% %inputB2%
set outputS=%errorlevel%
call:_And %inputA2% %inputB2%
set outputC=%errorlevel%
endlocal && set "outputS=%outputS%" && set "outputC=%outputC%"
exit /b
:: Function for the XOR-gate following the logic given
:_XOr
setlocal
set inputA1=%1
set inputB1=%2
call:_Not %inputA1%
set inputA2=%errorlevel%
call:_Not %inputB1%
set inputB2=%errorlevel%
call:_And %inputA1% %inputB2%
set inputA=%errorlevel%
call:_And %inputA2% %inputB1%
set inputB=%errorlevel%
call:_Or %inputA% %inputB%
set outputA=%errorlevel%
:: As there is only one output, we can use 'exit /b {errorlevel}' to return a specified errorlevel
exit /b %outputA%
:: The basic 3 logic gates that every other funtion is composed of
:_Not
setlocal
if %1==0 exit /b 1
exit /b 0
:_Or
setlocal
if %1==1 exit /b 1
if %2==1 exit /b 1
exit /b 0
:_And
setlocal
if %1==1 if %2==1 exit /b 1
exit /b 0
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Sidef
|
Sidef
|
var x = 42;
{ x += 1; say x }.fork.wait; # x is 43 here
say x; # but here is still 42
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Slate
|
Slate
|
p@(Process traits) forkAndDo: b
[| ret |
(ret := lobby cloneSystem)
first ifTrue: [p pipes addLast: ret second. ret second]
ifFalse: [[p pipes clear. p pipes addLast: ret second. b applyWith: ret second] ensure: [lobby quit]]
].
|
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
|
#Modula-3
|
Modula-3
|
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.)
|
#ALGOL_W
|
ALGOL W
|
begin
% calculate forward differences %
% sets elements of B to the first order forward differences of A %
% A should have bounds 1 :: n, B should have bounds 1 :: n - 1 %
procedure FirstOrderFDifference ( integer array A( * )
; integer array B( * )
; integer value n
) ;
for i := 2 until n do B( i - 1 ) := A( i ) - A( i - 1 );
integer array v ( 1 :: 10 );
integer array diff( 1 :: 9 );
integer vPos, length;
% construct the initial values array %
vPos := 1;
for i := 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 do begin
v( vPos ) := i;
vPos := vPos + 1
end for_i ;
% calculate and show the differences %
i_w := 5; % set output format %
length := 10;
for order := 1 until length - 1 do begin
FirstOrderFDifference( v, diff, length );
length := length - 1;
write( order, ": " ); for i := 1 until length do writeon( diff( i ) );
for i := 1 until length do v( i ) := diff( i )
end for_order
end.
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Ursala
|
Ursala
|
#show+
main = -[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.
|
#Julia
|
Julia
|
module FormalPowerSeries
using Printf
import Base.iterate, Base.eltype, Base.one, Base.show, Base.IteratorSize
import Base.IteratorEltype, Base.length, Base.size, Base.convert
_div(a, b) = a / b
_div(a::Union{Integer,Rational}, b::Union{Integer,Rational}) = a // b
abstract type AbstractFPS{T<:Number} end
Base.IteratorSize(::AbstractFPS) = Base.IsInfinite()
Base.IteratorEltype(::AbstractFPS) = Base.HasEltype()
Base.eltype(::AbstractFPS{T}) where T = T
Base.one(::AbstractFPS{T}) where T = ConstantFPS(one(T))
function Base.show(io::IO, fps::AbstractFPS{T}) where T
itr = Iterators.take(fps, 8)
a, s = iterate(itr)
print(io, a)
a, s = iterate(itr, s)
@printf(io, " %s %s⋅x",
ifelse(sign(a) ≥ 0, '+', '-'), abs(a))
local i = 2
while (it = iterate(itr, s)) != nothing
a, s = it
@printf(io, " %s %s⋅x^%i",
ifelse(sign(a) ≥ 0, '+', '-'), abs(a), i)
i += 1
end
print(io, "...")
end
struct MinusFPS{T,A<:AbstractFPS{T}} <: AbstractFPS{T}
a::A
end
Base.:-(a::AbstractFPS{T}) where T = MinusFPS{T,typeof(a)}(a)
function Base.iterate(fps::MinusFPS)
v, s = iterate(fps.a)
return -v, s
end
function Base.iterate(fps::MinusFPS, st)
v, s = iterate(fps.a, st)
return -v, s
end
struct SumFPS{T,A<:AbstractFPS,B<:AbstractFPS} <: AbstractFPS{T}
a::A
b::B
end
Base.:+(a::AbstractFPS{A}, b::AbstractFPS{B}) where {A,B} =
SumFPS{promote_type(A, B),typeof(a),typeof(b)}(a, b)
Base.:-(a::AbstractFPS, b::AbstractFPS) = a + (-b)
function Base.iterate(fps::SumFPS{T,A,B}) where {T,A,B}
a1, s1 = iterate(fps.a)
a2, s2 = iterate(fps.b)
return T(a1 + a2), (s1, s2)
end
function Base.iterate(fps::SumFPS{T,A,B}, st) where {T,A,B}
stateA, stateB = st
valueA, stateA = iterate(fps.a, stateA)
valueB, stateB = iterate(fps.b, stateB)
return T(valueA + valueB), (stateA, stateB)
end
struct ProductFPS{T,A<:AbstractFPS,B<:AbstractFPS} <: AbstractFPS{T}
a::A
b::B
end
Base.:*(a::AbstractFPS{A}, b::AbstractFPS{B}) where {A,B} =
ProductFPS{promote_type(A, B),typeof(a),typeof(b)}(a, b)
function Base.iterate(fps::ProductFPS{T}) where T
a1, s1 = iterate(fps.a)
a2, s2 = iterate(fps.b)
T(sum(a1 .* a2)), (s1, s2, T[a1], T[a2])
end
function Base.iterate(fps::ProductFPS{T,A,B}, st) where {T,A,B}
stateA, stateB, listA, listB = st
valueA, stateA = iterate(fps.a, stateA)
valueB, stateB = iterate(fps.b, stateB)
push!(listA, valueA)
pushfirst!(listB, valueB)
return T(sum(listA .* listB)), (stateA, stateB, listA, listB)
end
struct DifferentiatedFPS{T,A<:AbstractFPS} <: AbstractFPS{T}
a::A
end
differentiate(fps::AbstractFPS{T}) where T = DifferentiatedFPS{T,typeof(fps)}(fps)
function Base.iterate(fps::DifferentiatedFPS{T,A}) where {T,A}
_, s = iterate(fps.a)
return Base.iterate(fps, (zero(T), s))
end
function Base.iterate(fps::DifferentiatedFPS{T,A}, st) where {T,A}
n, s = st
n += one(n)
v, s = iterate(fps.a, s)
return n * v, (n, s)
end
struct IntegratedFPS{T,A<:AbstractFPS} <: AbstractFPS{T}
a::A
k::T
end
integrate(fps::AbstractFPS{T}, k::T=zero(T)) where T = IntegratedFPS{T,typeof(fps)}(fps, k)
integrate(fps::AbstractFPS{T}, k::T=zero(T)) where T <: Integer =
IntegratedFPS{Rational{T},typeof(fps)}(fps, k)
function Base.iterate(fps::IntegratedFPS{T,A}, st=(0, 0)) where {T,A}
if st == (0, 0)
return fps.k, (one(T), 0)
end
n, s = st
if n == one(T)
v, s = iterate(fps.a)
else
v, s = iterate(fps.a, s)
end
r::T = _div(v, n)
n += one(n)
return r, (n, s)
end
# Examples of FPS: constant
struct FiniteFPS{T} <: AbstractFPS{T}
v::NTuple{N,T} where N
end
Base.iterate(fps::FiniteFPS{T}, st=1) where T =
st > lastindex(fps.v) ? (zero(T), st) : (fps.v[st], st + 1)
Base.convert(::Type{FiniteFPS}, x::Real) = FiniteFPS{typeof(x)}((x,))
FiniteFPS(r) = convert(FiniteFPS, r)
for op in (:+, :-, :*)
@eval Base.$op(x::Number, a::AbstractFPS) = $op(FiniteFPS(x), a)
@eval Base.$op(a::AbstractFPS, x::Number) = $op(a, FiniteFPS(x))
end
struct ConstantFPS{T} <: AbstractFPS{T}
k::T
end
Base.iterate(c::ConstantFPS, ::Any=nothing) = c.k, nothing
struct SineFPS{T} <: AbstractFPS{T} end
SineFPS() = SineFPS{Rational{Int}}()
function Base.iterate(::SineFPS{T}, st=(0, 1, 1)) where T
n, fac, s = st
local r::T
if iseven(n)
r = zero(T)
else
r = _div(one(T), (s * fac))
s = -s
end
n += 1
fac *= n
return r, (n, fac, s)
end
struct CosineFPS{T} <: AbstractFPS{T} end
CosineFPS() = CosineFPS{Rational{Int}}()
function Base.iterate(::CosineFPS{T}, st=(0, 1, 1)) where T
n, fac, s = st
local r::T
if iseven(n)
r = _div(one(T), (s * fac))
else
r = zero(T)
s = -s
end
n += 1
fac *= n
return r, (n, fac, s)
end
end # module FormalPowerSeries
|
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.
|
#DBL
|
DBL
|
D5=7125
A10=D5,'-ZZZZX.XXX' ; 7.125
A10=D5,'-ZZZZX.XXX' [LEFT] ;7.125
A10=D5,'-XXXXX.XXX' ; 00007.125
A10=-D5,'-ZZZZX.XXX' ;- 7.125
A10=-D5,'-ZZZZX.XXX' [LEFT] ;- 7.125
A10=-D5,'-XXXXX.XXX' [LEFT] ;-00007.125
A10=-D5,'XXXXX.XXX-' ;00007.125-
A10=-D5,'ZZZZX.XXX-' ; 7.125-
A10=-D5,'ZZZZX.XXX-' [LEFT] ;7.125-
A10=1500055,'ZZZ,ZZX.XX ; 15,000.55
|
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.
|
#dc
|
dc
|
[*
* (n) (c) lpx
* Print number n, using at least c characters.
*
* Different from normal, this function:
* 1. Uses the current ibase (not the obase) to print the number.
* 2. Prunes "0" digits from the right, so [1.500 1 lxp] prints "1.5".
* 3. Pads "0" digits to the left, so [_1.5 6 lxp] prints "-001.5".
* 4. Never prints a newline.
*]sz
[
Sc Sn [Local n, c = from stack.]sz
K Ss [Local s = original scale.]sz
[Reserve local variables D, F, I, L.]sz
0 SD 0 SF 0 SI 0 SL
[ [If n < 0:]sz
[-]P [Print negative sign.]sz
lc 1 - sc [Decrement c.]sz
0 ln - sn [Negate n.]sz
]sI 0 ln <I
[*
* Array D[] takes digits before the radix point.
*]sz
0 k [scale = 0]sz
0 Sd [Local d = 0]sz
ln 1 / [Push digits before radix point.]sz
[ [Loop to fill D[]:]sz
d 10 % ld :D [D[d] = next digit.]sz
ld 1 + sd [Increment d.]sz
10 / [Remove digit.]sz
d 0 !=L [Loop until no digits.]sz
]sL d 0 !=L
sz [Pop digits.]sz
[*
* Array F[] takes digits after the radix point.
*]sz
ln ln 1 / - [Push digits after radix point.]sz
d X k [scale = enough.]sz
_1 Sf [Local f = -1]sz
d 1 + [Push 1 + digits after radix point.]sz
[ [Loop to count digits:]sz
lf 1 + sf [Increment f.]sz
10 / [Remove digit.]sz
d 0 !=L [Loop until no digits.]sz
]sL d 0 !=L
sz [Pop 1 + digits.]sz
0 k [scale = 0]sz
10 lf ^ * 1 / [Remove radix point from digits.]sz
[ [Loop to prune digits:]sz
lf 1 - sf [Decrement f.]sz
10 / [Remove digit.]sz
d 10 % 0 =L [Loop while last digit is 0.]sz
]sL d 10 % 0 =L
0 Si [Local i = 0]sz
[ [Loop to fill F[]:]sz
d 10 % li :F [F[i] = next digit.]sz
10 / [Remove digit.]sz
li 1 + si [Increment i.]sz
lf li <L [Loop while i < f.]sz
]sL lf li <L
sz [Pop digits.]sz
lc ld - [Push count = c - d.]sz
[ [If f > 0:]sz
1 lf + - [Subtract 1 radix point + f from count.]sz
]sI 0 lf >I
[ [Loop:]sz
[0]P [Print a padding "0".]sz
1 - [Decrement count.]sz
d 0 <L [Loop while count > 0.]sz
]sL d 0 <L
sz [Pop count.]sz
[ [Local function (digit) lPx:]sz
[ [Execute:]sz
[*
* Push the string that matches the digit.
*]sz
[[0] 2Q]sI d 0 =I [[1] 2Q]sI d 1 =I [[2] 2Q]sI d 2 =I [[3] 2Q]sI d 3 =I
[[4] 2Q]sI d 4 =I [[5] 2Q]sI d 5 =I [[6] 2Q]sI d 6 =I [[7] 2Q]sI d 7 =I
[[8] 2Q]sI d 8 =I [[9] 2Q]sI d 9 =I [[A] 2Q]sI d A =I [[B] 2Q]sI d B =I
[[C] 2Q]sI d C =I [[D] 2Q]sI d D =I [[E] 2Q]sI d E =I [[F] 2Q]sI d F =I
[?] [Else push "?".]sz
]x
P [Print the string.]sz
sz [Pop the digit.]sz
]SP
ld [Push counter = d.]sz
[ [Loop:]sz
1 - [Decrement counter.]sz
d ;D lPx [Print digit D[counter].]sz
d 0 <L [Loop while counter > 0.]sz
]sL d 0 <L
sz [Pop counter.]sz
[ [If f > 0:]sz
[.]P [Print radix point.]sz
lf [Push counter = f.]sz
[ [Loop:]sz
1 - [Decrement counter.]sz
d ;F lPx [Print digit F[counter].]sz
d 0 <L [Loop while counter > 0.]sz
]sL d 0 <L
sz [Pop counter.]sz
]sI 0 lf >I
[Restore variables n, c, d, f, D, F, L, I, P.]sz
Lnsz Lcsz Ldsz Lfsz LDsz LFsz LLsz LIsz LPsz
Ls k [Restore variable s. Restore original scale.]sz
]sp
|
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).
|
#C
|
C
|
#include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
/* a NOT that does not soil the rest of the host of the single bit */
#define NOT(X) (~(X)&1)
/* a shortcut to "implement" a XOR using only NOT, AND and OR gates, as
task requirements constrain */
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(/*INPUT*/a, b, /*OUTPUT*/ps, pc);
halfadder(/*INPUT*/ps, ic, /*OUTPUT*/s, tc);
V(oc) = V(tc) | V(pc);
}
void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
IN b0, IN b1, IN b2, IN b3,
OUT o0, OUT o1, OUT o2, OUT o3,
OUT overflow)
{
PIN(zero); V(zero) = 0;
PIN(tc0); PIN(tc1); PIN(tc2);
fulladder(/*INPUT*/a0, b0, zero, /*OUTPUT*/o0, tc0);
fulladder(/*INPUT*/a1, b1, tc0, /*OUTPUT*/o1, tc1);
fulladder(/*INPUT*/a2, b2, tc1, /*OUTPUT*/o2, tc2);
fulladder(/*INPUT*/a3, b3, tc2, /*OUTPUT*/o3, overflow);
}
int main()
{
PIN(a0); PIN(a1); PIN(a2); PIN(a3);
PIN(b0); PIN(b1); PIN(b2); PIN(b3);
PIN(s0); PIN(s1); PIN(s2); PIN(s3);
PIN(overflow);
V(a3) = 0; V(b3) = 1;
V(a2) = 0; V(b2) = 1;
V(a1) = 1; V(b1) = 1;
V(a0) = 0; V(b0) = 0;
fourbitsadder(a0, a1, a2, a3, /* INPUT */
b0, b1, b2, b3,
s0, s1, s2, s3, /* OUTPUT */
overflow);
printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
V(a3), V(a2), V(a1), V(a0),
V(b3), V(b2), V(b1), V(b0),
V(s3), V(s2), V(s1), V(s0),
V(overflow));
return 0;
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Smalltalk
|
Smalltalk
|
'Here I am' displayNl.
|a|
a := [
(Delay forSeconds: 2) wait .
1 to: 100 do: [ :i | i displayNl ]
] fork.
'Child will start after 2 seconds' displayNl.
"wait to avoid terminating first the parent;
a better way should use semaphores"
(Delay forSeconds: 10) wait.
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Standard_ML
|
Standard ML
|
case Posix.Process.fork () of
SOME pid => print "This is the original process\n"
| NONE => print "This is the new process\n";
|
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
|
#MUMPS
|
MUMPS
|
MULTIPLY(A,B);Returns the product of A and B
QUIT 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.)
|
#APL
|
APL
|
list ← 90 47 58 29 22 32 55 5 55 73
fd ← {⍺=0:⍵⋄(⍺-1)∇(1↓⍵)-(¯1↓⍵)}
1 fd list
¯43 11 ¯29 ¯7 10 23 ¯50 50 18
2 fd list
54 ¯40 22 17 13 ¯73 100 ¯32
|
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.)
|
#AppleScript
|
AppleScript
|
-- forwardDifference :: Num a => [a] -> [a]
on forwardDifference(xs)
zipWith(my subtract, xs, rest of xs)
end forwardDifference
-- nthForwardDifference :: Num a => Int -> [a] -> [a]
on nthForwardDifference(xs, i)
|index|(iterate(forwardDifference, xs), 1 + i)
end nthForwardDifference
-------------------------- TEST ---------------------------
on run
script show
on |λ|(xs, i)
((i - 1) as string) & " -> " & showList(xs)
end |λ|
end script
unlines(map(show, ¬
take(10, ¬
iterate(forwardDifference, ¬
{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}))))
end run
-------------------- GENERIC FUNCTIONS --------------------
-- Just :: a -> Maybe a
on Just(x)
-- Constructor for an inhabited Maybe (option type) value.
-- Wrapper containing the result of a computation.
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
-- Constructor for an empty Maybe (option type) value.
-- Empty wrapper returned where a computation is not possible.
{type:"Maybe", Nothing:true}
end Nothing
-- index (!!) :: [a] -> Int -> Maybe a
-- index (!!) :: Gen [a] -> Int -> Maybe a
-- index (!!) :: String -> Int -> Maybe Char
on |index|(xs, i)
if script is class of xs then
repeat with j from 1 to i
set v to |λ|() of xs
end repeat
if missing value is not v then
Just(v)
else
Nothing()
end if
else
if length of xs < i then
Nothing()
else
Just(item i of xs)
end if
end if
end |index|
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set str to xs as text
set my text item delimiters to dlm
str
end intercalate
-- iterate :: (a -> a) -> a -> Gen [a]
on iterate(f, x)
script
property v : missing value
property g : mReturn(f)'s |λ|
on |λ|()
if missing value is v then
set v to x
else
set v to g(v)
end if
return v
end |λ|
end script
end iterate
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- showList :: [a] -> String
on showList(xs)
"[" & intercalate(", ", map(my str, xs)) & "]"
end showList
-- str :: a -> String
on str(x)
x as string
end str
-- subtract :: Num -> Num -> Num
on subtract(x, y)
y - x
end subtract
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith
|
http://rosettacode.org/wiki/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
|
#.E0.AE.89.E0.AE.AF.E0.AE.BF.E0.AE.B0.E0.AF.8D.2FUyir
|
உயிர்/Uyir
|
முதன்மை என்பதின் வகை எண் பணி {{
("உலகத்தோருக்கு வணக்கம்") என்பதை திரை.இடு;
முதன்மை = 0;
}};
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.2.10
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
class Frac : Comparable<Frac> {
val num: Long
val denom: Long
companion object {
val ZERO = Frac(0, 1)
val ONE = Frac(1, 1)
}
constructor(n: Long, d: Long) {
require(d != 0L)
var nn = n
var dd = d
if (nn == 0L) {
dd = 1
}
else if (dd < 0) {
nn = -nn
dd = -dd
}
val g = Math.abs(gcd(nn, dd))
if (g > 1) {
nn /= g
dd /= g
}
num = nn
denom = dd
}
constructor(n: Int, d: Int) : this(n.toLong(), d.toLong())
operator fun plus(other: Frac) =
Frac(num * other.denom + denom * other.num, other.denom * denom)
operator fun unaryPlus() = this
operator fun unaryMinus() = Frac(-num, denom)
operator fun minus(other: Frac) = this + (-other)
operator fun times(other: Frac) =
Frac(this.num * other.num, this.denom * other.denom)
operator fun rem(other: Frac) = this - Frac((this / other).toLong(), 1) * other
operator fun inc() = this + ONE
operator fun dec() = this - ONE
fun inverse(): Frac {
require(num != 0L)
return Frac(denom, num)
}
operator fun div(other: Frac) = this * other.inverse()
fun abs() = if (num >= 0) this else -this
override fun compareTo(other: Frac): Int {
val diff = this.toDouble() - other.toDouble()
return when {
diff < 0.0 -> -1
diff > 0.0 -> +1
else -> 0
}
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is Frac) return false
return this.compareTo(other) == 0
}
override fun hashCode() = num.hashCode() xor denom.hashCode()
override fun toString() = if (denom == 1L) "$num" else "$num/$denom"
fun toDouble() = num.toDouble() / denom
fun toLong() = num / denom
}
interface Gene {
fun coef(n: Int): Frac
}
class Term(private val gene: Gene) {
private val cache = mutableListOf<Frac>()
operator fun get(n: Int): Frac {
if (n < 0) return Frac.ZERO
if (n >= cache.size) {
for (i in cache.size..n) cache.add(gene.coef(i))
}
return cache[n]
}
}
class FormalPS {
private lateinit var term: Term
private companion object {
const val DISP_TERM = 12
const val X_VAR = "x"
}
constructor() {}
constructor(term: Term) {
this.term = term
}
constructor(polynomial: List<Frac>) :
this(Term(object : Gene {
override fun coef(n: Int) =
if (n < 0 || n >= polynomial.size)
Frac.ZERO
else
polynomial[n]
}))
fun copyFrom(other: FormalPS) {
term = other.term
}
fun inverseCoef(n: Int): Frac {
val res = Array(n + 1) { Frac.ZERO }
res[0] = term[0].inverse()
for (i in 1..n) {
for (j in 0 until i) res[i] += term[i - j] * res[j]
res[i] *= -res[0]
}
return res[n]
}
operator fun plus(other: FormalPS) =
FormalPS(Term(object : Gene {
override fun coef(n: Int) = term[n] + other.term[n]
}))
operator fun minus(other: FormalPS) =
FormalPS(Term(object : Gene {
override fun coef(n: Int) = term[n] - other.term[n]
}))
operator fun times(other: FormalPS) =
FormalPS(Term(object : Gene {
override fun coef(n: Int): Frac {
var res = Frac.ZERO
for (i in 0..n) res += term[i] * other.term[n - i]
return res
}
}))
operator fun div(other: FormalPS) =
FormalPS(Term(object : Gene {
override fun coef(n: Int): Frac {
var res = Frac.ZERO
for (i in 0..n) res += term[i] * other.inverseCoef(n - i)
return res
}
}))
fun diff() =
FormalPS(Term(object : Gene {
override fun coef(n: Int) = term[n + 1] * Frac(n + 1, 1)
}))
fun intg() =
FormalPS(Term(object : Gene {
override fun coef(n: Int) =
if (n == 0) Frac.ZERO else term[n - 1] * Frac(1, n)
}))
override fun toString() = toString(DISP_TERM)
private fun toString(dpTerm: Int): String {
val sb = StringBuilder()
var c = term[0]
if (c != Frac.ZERO) sb.append(c.toString())
for (i in 1 until dpTerm) {
c = term[i]
if (c != Frac.ZERO) {
if (c > Frac.ZERO && sb.length > 0) sb.append(" + ")
sb.append (when {
c == Frac.ONE -> X_VAR
c == -Frac.ONE -> " - $X_VAR"
c.num < 0 -> " - ${-c}$X_VAR"
else -> "$c$X_VAR"
})
if (i > 1) sb.append("^$i")
}
}
if (sb.length == 0) sb.append("0")
sb.append(" + ...")
return sb.toString()
}
}
fun main(args: Array<String>) {
var cos = FormalPS()
val sin = cos.intg()
cos.copyFrom(FormalPS(listOf(Frac.ONE)) - sin.intg())
println("SIN(x) = $sin")
println("COS(x) = $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.
|
#Delphi
|
Delphi
|
program FormattedNumericOutput;
{$APPTYPE CONSOLE}
uses
SysUtils;
const
fVal = 7.125;
begin
Writeln(FormatFloat('0000#.000',fVal));
Writeln(FormatFloat('0000#.0000000',fVal));
Writeln(FormatFloat('##.0000000',fVal));
Writeln(FormatFloat('0',fVal));
Writeln(FormatFloat('#.#E-0',fVal));
Writeln(FormatFloat('#,##0.00;;Zero',fVal));
Readln;
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).
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks.FourBitAdder
{
public struct BitAdderOutput
{
public bool S { get; set; }
public bool C { get; set; }
public override string ToString ( )
{
return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" );
}
}
public struct Nibble
{
public bool _1 { get; set; }
public bool _2 { get; set; }
public bool _3 { get; set; }
public bool _4 { get; set; }
public override string ToString ( )
{
return ( _4 ? "1" : "0" )
+ ( _3 ? "1" : "0" )
+ ( _2 ? "1" : "0" )
+ ( _1 ? "1" : "0" );
}
}
public struct FourBitAdderOutput
{
public Nibble N { get; set; }
public bool C { get; set; }
public override string ToString ( )
{
return N.ToString ( ) + "c" + ( C ? "1" : "0" );
}
}
public static class LogicGates
{
// Basic Gates
public static bool Not ( bool A ) { return !A; }
public static bool And ( bool A, bool B ) { return A && B; }
public static bool Or ( bool A, bool B ) { return A || B; }
// Composite Gates
public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }
}
public static class ConstructiveBlocks
{
public static BitAdderOutput HalfAdder ( bool A, bool B )
{
return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };
}
public static BitAdderOutput FullAdder ( bool A, bool B, bool CI )
{
BitAdderOutput HA1 = HalfAdder ( CI, A );
BitAdderOutput HA2 = HalfAdder ( HA1.S, B );
return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };
}
public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )
{
BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );
BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );
BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );
BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );
return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };
}
public static void Test ( )
{
Console.WriteLine ( "Four Bit Adder" );
for ( int i = 0; i < 256; i++ )
{
Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
if ( (i & 1) == 1)
{
A._1 = true;
}
if ( ( i & 2 ) == 2 )
{
A._2 = true;
}
if ( ( i & 4 ) == 4 )
{
A._3 = true;
}
if ( ( i & 8 ) == 8 )
{
A._4 = true;
}
if ( ( i & 16 ) == 16 )
{
B._1 = true;
}
if ( ( i & 32 ) == 32)
{
B._2 = true;
}
if ( ( i & 64 ) == 64 )
{
B._3 = true;
}
if ( ( i & 128 ) == 128 )
{
B._4 = true;
}
Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );
}
Console.WriteLine ( );
}
}
}
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Symsyn
|
Symsyn
|
| parent
ssx 'R child'
wait 'childevent'
'child is running...' []
'child will end...' []
post 'dieevent'
delay 5000
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Tcl
|
Tcl
|
package require Expect
# or
package require Tclx
for {set i 0} {$i < 100} {incr i} {
set pid [fork]
switch $pid {
-1 {
puts "Fork attempt #$i failed."
}
0 {
puts "I am child process #$i."
exit
}
default {
puts "The parent just spawned child process #$i."
}
}
}
|
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
|
#11l
|
11l
|
V Small = [‘zero’, ‘one’, ‘two’, ‘three’, ‘four’,
‘five’, ‘six’, ‘seven’, ‘eight’, ‘nine’,
‘ten’, ‘eleven’, ‘twelve’, ‘thirteen’, ‘fourteen’,
‘fifteen’, ‘sixteen’, ‘seventeen’, ‘eighteen’, ‘nineteen’]
V Tens = [‘’, ‘’, ‘twenty’, ‘thirty’, ‘forty’, ‘fifty’, ‘sixty’, ‘seventy’, ‘eighty’, ‘ninety’]
V Illions = [‘’, ‘ thousand’, ‘ million’, ‘ billion’, ‘ trillion’, ‘ quadrillion’, ‘ quintillion’]
F say(Int64 =n) -> String
V result = ‘’
I n < 0
result = ‘negative ’
n = -n
I n < 20
result ‘’= Small[Int(n)]
E I n < 100
result ‘’= Tens[Int(n I/ 10)]
V m = n % 10
I m != 0
result ‘’= ‘-’Small[Int(m)]
E I n < 1000
result ‘’= Small[Int(n I/ 100)]‘ hundred’
V m = n % 100
I m != 0
result ‘’= ‘ ’say(m)
E
V sx = ‘’
V i = 0
L n > 0
V m = n % 1000
n I/= 1000
I m != 0
V ix = say(m)‘’Illions[i]
I sx.len > 0
ix ‘’= ‘ ’sx
sx = ix
i++
result ‘’= sx
R result
F fourIsMagic(=n)
V s = say(n).capitalize()
V result = s
L n != 4
n = s.len
s = say(n)
result ‘’= ‘ is ’s‘, ’s
R result‘ is magic.’
L(n) [Int64(0), 4, 6, 11, 13, 75, 100, 337, -164, 7FFF'FFFF'FFFF'FFFF]
print(fourIsMagic(n))
|
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
|
#Nanoquery
|
Nanoquery
|
def multiply(a, b)
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.)
|
#Arturo
|
Arturo
|
; element-wise subtraction of two blocks. e.g.
; vsub [1 2 3] [1 2 3] ; [0 0 0]
vsub: function [u v][
map couple u v 'pair -> pair\0 - pair\1
]
differences: function [block][
order: attr "order"
if order = null -> order: 1
loop 1..order 'n -> block: vsub block drop block 1
return block
]
print differences .order: 4 [90.5 47 58 29 22 32 55 5 55 73.5]
print differences [1 2 3 4 5 6 7]
|
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
|
#V
|
V
|
"Hello world!" puts
|
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.
|
#Lua
|
Lua
|
powerseries = setmetatable({
__add = function(z1, z2) return powerseries(function(n) return z1.coeff(n) + z2.coeff(n) end) end,
__sub = function(z1, z2) return powerseries(function(n) return z1.coeff(n) - z2.coeff(n) end) end,
__mul = function(z1, z2) return powerseries(function(n)
local ret = 0
for i = 0, n do
ret = ret + z1.coeff(i) * z2.coeff(n-i)
end
return ret
end) end,
__div = function(z1, z2) return powerseries(function(n)
local ret = z1.coeff(n)
local function coeffs(a)
local c = z1.coeff(a)
for j = 0, a - 1 do c = c - coeffs(j) * z2.coeff(a-j) end
return c / z2.coeff(0)
end
for i = 0, n-1 do
ret = ret - coeffs(i) * z2.coeff(n-i)
end
return ret / z2.coeff(0)
end) end,
__pow = function(z1, p) -- for a series z, z^n returns the nth derivative of z. negative values take integrals.
if p == 0 then return z1
elseif p > 0 then return powerseries(function(i) return z1.coeff(i+1)*(i+1) end)^(p-1)
else return powerseries(function(i) return z1.coeff(i-1)/i end)^(p+1)
end
end,
__unm = function(z1) return powerseries(function(n) return -z1.coeff(n) end) end,
__index = function(z, n) return z.coeff(n) end,
__call = function(z, n)
local ret = 0
for i = 0, 15 do --we do 20 terms, which is simpler than trying to check error bounds
ret = ret + z[i]*(n^i)
end
return ret
end},
{__call = function(z, f) return setmetatable({coeff = f}, z) end})
cosine = powerseries(function(n)
if(n == 0) then return 1
else return -((sine^(-1))[n]) --defer to the integral of sine function
end
end)
sine = powerseries(function(n)
if(n == 0) then return 0
else return (cosine^(-1))[n] --defer to the integral of cosine function
end
end)
print(sine[1], sine[3], sine[5], sine[7], cosine[0], cosine[2], cosine[4], cosine[6])
print(sine(math.pi/3), sine(math.pi/2), cosine(math.pi/3), cosine(math.pi/2))
tangent = sine / cosine
print(tangent(math.pi/3), tangent(math.pi/4), tangent(math.pi/6)) --something like 30000 function calls!
|
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.
|
#Eiffel
|
Eiffel
|
note
description : "{
2 Examples are given.
The first example uses the standard library's FORMAT_DOUBLE class.
The second example uses the AEL_PRINTF class from the freely available
Amalasoft Eiffel Library (AEL).
See additional comments in the code.
}"
class APPLICATION
inherit
AEL_PRINTF -- Optional, see below
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
print_formatted_std (7.125)
print_formatted_ael (7.125)
end
--|--------------------------------------------------------------
print_formatted_std (v: REAL_64)
-- Print the value 'v' as a zero-padded string in a fixed
-- overall width of 9 places and, with a precision of
-- to 3 places to the right of the decimal point.
-- Use the FORMAT_DOUBLE class from the standard library
local
fmt: FORMAT_DOUBLE
do
create fmt.make (9, 3)
fmt.zero_fill
print (fmt.formatted (v) + "%N")
end
--|--------------------------------------------------------------
print_formatted_ael (v: REAL_64)
-- Print the value 'v' as a zero-padded string in a fixed
-- overall width of 9 places and, with a precision of
-- to 3 places to the right of the decimal point.
-- Use the AEL_PRINTF class from the Amalasoft Eiffel Library
-- freely available from www.amalasoft.com
do
-- printf accepts a format string and an argument list
-- The argument list is a container (often a manifest
-- array) of values corresponding to the type of the format
-- specified in the format string argument.
-- When only one argument is needed, then there is also the
-- option to use just the value, without the container.
-- In this example, the line would be:
-- printf ("%%09.3f%N", v)
-- The more deliberate form is used in the actual example,
-- as it is more representative of common usage, when there
-- are multiple value arguments.
printf ("%%09.3f%N", << v >>)
end
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).
|
#C.2B.2B
|
C++
|
(ns rosettacode.adder
(:use clojure.test))
(defn xor-gate [a b]
(or (and a (not b)) (and b (not a))))
(defn half-adder [a b]
"output: (S C)"
(cons (xor-gate a b) (list (and a b))))
(defn full-adder [a b c]
"output: (C S)"
(let [HA-ca (half-adder c a)
HA-ca->sb (half-adder (first HA-ca) b)]
(cons (or (second HA-ca) (second HA-ca->sb))
(list (first HA-ca->sb)))))
(defn n-bit-adder
"first bits on the list are low order bits
1 = true
2 = false true
3 = true true
4 = false false true..."
can add numbers of different bit-length
([a-bits b-bits] (n-bit-adder a-bits b-bits false))
([a-bits b-bits carry]
(let [added (full-adder (first a-bits) (first b-bits) carry)]
(if(and (nil? a-bits) (nil? b-bits))
(if carry (list carry) '())
(cons (second added) (n-bit-adder (next a-bits) (next b-bits) (first added)))))))
;use:
(n-bit-adder [true true true true true true] [true true true true true true])
=> (false true true true true true true)
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Toka
|
Toka
|
needs shell
getpid is-data PID
[ fork getpid PID = [ ." Child PID: " . cr ] [ ." In child\n" ] ifTrueFalse ] invoke
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#UNIX_Shell
|
UNIX Shell
|
i=0
(while test $i -lt 10; do
sleep 1
echo "Child process"
i=`expr $i + 1`
done) &
while test $i -lt 5; do
sleep 2
echo "Parent process"
i=`expr $i + 1`
done
|
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
|
#8086_Assembly
|
8086 Assembly
|
puts: equ 9h ; MS-DOS syscall to print a string
cpu 8086
bits 16
org 100h
section .text
;;; Read number from the MS-DOS command line
;;; The task says numbers up to 999999 need to be
;;; supported, so we can't get away with using MUL.
mov cl,[80h] ; Is there an argument?
test cl,cl
jnz havearg
mov ah,puts ; If not, print "no input"
mov dx,errinput
int 21h
ret ; And stop.
havearg: mov si,82h ; Start of argument string
xor ch,ch ; CX = argument length
dec cx ; Minus one (space before argument)
xor ax,ax ; Accumulator starts out at 0
xor dx,dx
numloop: mov bp,ax ; DX:AX *= 10
mov di,dx
add ax,ax ; ... *2
adc dx,dx
add ax,ax ; ... *4
adc dx,dx
add ax,bp ; ... *5
adc dx,di
add ax,ax ; ... *10
adc dx,dx
mov bx,ax
lodsb ; Get digit
sub al,'0'
xor ah,ah
add ax,bx ; Add digit
adc dx,0
loop numloop ; Next digit if there is one
;;; DX:AX now contains the binary representation of
;;; the decimal input.
cmp dx,0Fh ; Check that DX:AX <= 999999
jb donum
cmp ax,4240h ; 0F4240h = 1000000
jb donum
mov ah,puts ; Otherwise, print error message
mov dx,errhigh
int 21h
ret
;;; DX:AX = current number
donum: push dx ; Keep number
push ax
mov di,numstring ; Create the string for the number
call cardinal
mov [di],byte '$'
xor [numstring],byte 32 ; Capitalize first letter
.print: mov dx,numstring ; Print the string
mov ah,puts
int 21h
mov dx,is ; print ' is ',
int 21h
pop ax ; Retrieve number
pop dx
test dx,dx ; DX:AX = 4 = magic
jnz .nomagic ; DX <> 0 = not magic
cmp ax,4 ; If AX=4 then magic
je .magic
.nomagic: sub di,numstring ; Calculate length of string
xor dx,dx ; Set DX:AX to DI
mov ax,di
push dx ; Store new number on stack
push ax
mov di,numstring ; Make string for new number
call cardinal
mov [di],byte '$'
mov dx,numstring ; Print the string
mov ah,puts
int 21h
mov dx,commaspace ; Print comma and space
int 21h
jmp .print ; Then use next number as input
.magic: mov dx,magic ; print "magic.",
mov ah,puts
int 21h
ret ; and stop
;;; Subroutine: assuming 0 <= DX:AX <= 999999, write
;;; cardinal representation at ES:DI.
cardinal: mov bp,ax
or bp,dx
jz .zero ; If it is zero, return 'Zero'
mov bp,1000 ; Otherwise, get 1000s part
div bp
test ax,ax ; Above 1000?
jz .hundreds_dx ; If not, just find hundreds
push dx ; Otherwise, save <1000s part,
call .hundreds ; get string for how many thousands,
mov si,thousand ; Then add ' thousand',
call stradd
pop dx ; Restore <1000 part,
test dx,dx ; Even thousands?
jnz .hundreds_spc ; Then add hundreds
ret ; Otherwise we're done
.hundreds_spc: mov al,' ' ; Add space betweeen thousand and rest
stosb
.hundreds_dx: mov ax,dx
.hundreds: mov bp,100 ; Get hundreds part
xor dx,dx
div bp ; AX=100s
test ax,ax ; If zero, no hundreds
jz .tens_dx
dec ax ; Otherwise, look up in singles
shl ax,1 ; table,
mov bx,ax
mov si,[single+bx]
call stradd ; Add to the output string,
mov si,hundred ; Add ' hundred',
call stradd
test dx,dx ; Is there any more?
jne .tens_spc ; If so, add tens
ret ; Otherwise we're done
.tens_spc: mov al,' ' ; Add space between 'hundred' and tens
stosb
.tens_dx: mov ax,dx ; Tens in AX (from hundreds)
.tens: aam ; AH=10s digit, AL=1s digit
test ah,ah ; If 10s digit is 0, single digit
jz .ones
cmp ah,1 ; If 10s digit is 1, teens
jz .teens
mov bl,ah ; Look up tens digit in tens table
sub bl,2
shl bl,1
xor bh,bh
mov si,[tens+bx] ; Add to the output string
call stradd
test al,al ; Ones digit left?
jne .ones_dash ; If so, add dash and ones digit
ret ; Otherwise we're done
.ones_dash: mov [di],byte '-'
inc di
.ones: mov bl,al ; Look up ones digit in ones table
dec bl
shl bl,1
xor bh,bh
mov si,[single+bx]
jmp stradd
.teens: mov bl,al ; Look up ones digit in teens table
shl bl,1
xor bh,bh
mov si,[teens+bx]
jmp stradd
.zero: mov si,zero
;;; Copy $-terminated string at DS:SI to ES:DI, except
;;; the terminator.
stradd: push ax ; Keep AX register
.loop: lodsb ; Get byte from DS:SI
cmp al,'$' ; Are we there yet?
je .out ; If so, stop
stosb ; Otherwise, store at ES:DI
jmp .loop
.out: pop ax
ret
section .data
single: dw one,two,three,four
dw five,six,seven,eight,nine
teens: dw ten,eleven,twelve,thirteen,fourteen
dw fifteen,sixteen,seventeen,eighteen,nineteen
tens: dw twenty,thirty,forty,fifty
dw sixty,seventy,eighty,ninety
zero: db 'zero$'
one: db 'one$'
two: db 'two$'
three: db 'three$'
four: db 'four$'
five: db 'five$'
six: db 'six$'
seven: db 'seven$'
eight: db 'eight$'
nine: db 'nine$'
ten: db 'ten$'
eleven: db 'eleven$'
twelve: db 'twelve$'
thirteen: db 'thirteen$'
fourteen: db 'fourteen$'
fifteen: db 'fifteen$'
sixteen: db 'sixteen$'
seventeen: db 'seventeen$'
eighteen: db 'eighteen$'
nineteen: db 'nineteen$'
twenty: db 'twenty$'
thirty: db 'thirty$'
forty: db 'forty$'
fifty: db 'fifty$'
sixty: db 'sixty$'
seventy: db 'seventy$'
eighty: db 'eighty$'
ninety: db 'ninety$'
hundred: db ' hundred$'
thousand: db ' thousand$'
is: db ' is $'
magic: db 'magic.$'
commaspace: db ', $'
errinput: db 'No input$'
errhigh: db 'Max input 999999$'
section .bss
numstring: resb 1024
|
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
|
#Neko
|
Neko
|
var multiply = function(a, b) {
a * b
}
$print(multiply(2, 3))
|
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.)
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % diff("2,3,4,3",1)
MsgBox % diff("2,3,4,3",2)
MsgBox % diff("2,3,4,3",3)
MsgBox % diff("2,3,4,3",4)
diff(list,ord) { ; high order forward differences of a list
Loop %ord% {
L =
Loop Parse, list, `, %A_Space%%A_Tab%
If (A_Index=1)
p := A_LoopField
Else
L .= "," A_LoopField-p, p := A_LoopField
list := SubStr(L,2)
}
Return list
}
|
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
|
#Vala
|
Vala
|
void main(){
stdout.printf("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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
cos = Series[Cos[x], {x, 0, 10}];
sin = Series[Sin[x], {x, 0, 8}];
sin - Integrate[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.
|
#Elixir
|
Elixir
|
n = 7.125
:io.fwrite "~f~n", [n]
:io.fwrite "~.3f~n", [n]
:io.fwrite "~9f~n", [n]
:io.fwrite "~9.3f~n", [n]
:io.fwrite "~9..0f~n", [n]
:io.fwrite "~9.3.0f~n", [n]
:io.fwrite "~9.3._f~n", [n]
:io.fwrite "~f~n", [-n]
:io.fwrite "~9.3f~n", [-n]
:io.fwrite "~9.3.0f~n", [-n]
:io.fwrite "~e~n", [n]
:io.fwrite "~12.4e~n", [n]
:io.fwrite "~12.4.0e~n", [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.
|
#Emacs_Lisp
|
Emacs Lisp
|
(format "%09.3f" 7.125) ;=> "00007.125"
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#Clojure
|
Clojure
|
(ns rosettacode.adder
(:use clojure.test))
(defn xor-gate [a b]
(or (and a (not b)) (and b (not a))))
(defn half-adder [a b]
"output: (S C)"
(cons (xor-gate a b) (list (and a b))))
(defn full-adder [a b c]
"output: (C S)"
(let [HA-ca (half-adder c a)
HA-ca->sb (half-adder (first HA-ca) b)]
(cons (or (second HA-ca) (second HA-ca->sb))
(list (first HA-ca->sb)))))
(defn n-bit-adder
"first bits on the list are low order bits
1 = true
2 = false true
3 = true true
4 = false false true..."
can add numbers of different bit-length
([a-bits b-bits] (n-bit-adder a-bits b-bits false))
([a-bits b-bits carry]
(let [added (full-adder (first a-bits) (first b-bits) carry)]
(if(and (nil? a-bits) (nil? b-bits))
(if carry (list carry) '())
(cons (second added) (n-bit-adder (next a-bits) (next b-bits) (first added)))))))
;use:
(n-bit-adder [true true true true true true] [true true true true true true])
=> (false true true true true true true)
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#UnixPipes
|
UnixPipes
|
(echo "Process 1" >&2 ;sleep 5; echo "1 done" ) | (echo "Process 2";cat;echo "2 done")
|
http://rosettacode.org/wiki/Fork
|
Fork
|
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Module1
Sub Fork()
Console.WriteLine("Spawned Thread")
End Sub
Sub Main()
Dim t As New System.Threading.Thread(New Threading.ThreadStart(AddressOf Fork))
t.Start()
Console.WriteLine("Main Thread")
t.Join()
End Sub
End Module
|
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
|
#APL
|
APL
|
magic←{
t20←'one' 'two' 'three' 'four' 'five' 'six' 'seven' 'eight' 'nine'
t20←t20,'ten' 'eleven' 'twelve' 'thirteen' 'fourteen' 'fifteen' 'sixteen'
t20←t20,'seventeen' 'eighteen' 'nineteen'
tens←'twenty' 'thirty' 'forty' 'fifty' 'sixty' 'seventy' 'eighty' 'ninety'
spell←{
⍵=0:'zero'
{
⍵=0:''
⍵<20:⍵⊃t20
⍵<100:∊tens[(⌊⍵÷10)-1],((0≠≢r)/'-'),r←∇10|⍵
⍵<1000:(∇⌊⍵÷100),' hundred',((0≠≢r)/' '),r←∇100|⍵
⍵<1e6:(∇⌊⍵÷1000),' thousand',((0≠≢r)/' '),r←∇1000|⍵
⍵<1e9:(∇⌊⍵÷1e6),' million',((0≠≢r)/' '),r←∇1e6|⍵
⍵<1e12:(∇⌊⍵÷1e9),' billion',((0≠≢r)/' '),r←∇1e9|⍵
⍵<1e15:(∇⌊⍵÷1e12),' trillion',((0≠≢r)/' '),r←∇1e12|⍵
⍵<1e18:(∇⌊⍵÷1e15),' quadrillion',((0≠≢r)/' '),r←∇1e15|⍵
⍵<1e21:(∇⌊⍵÷1e18),' quintillion',((0≠≢r)/' '),r←∇1e18|⍵
'Overflow' ⎕SIGNAL 11
}⍵
}
1(819⌶)@1⊢{
n←spell ⍵
⍵=4:n,' is magic.'
n,' is ',(spell ≢n),', ',∇≢n
}⍵
}
|
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
|
#AppleScript
|
AppleScript
|
(* Uses a Foundation number formatter for brevity. *)
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on getNumberFormatter(localeID, numberStyle)
set formatter to current application's class "NSNumberFormatter"'s new()
tell formatter to setLocale:(current application's class "NSLocale"'s localeWithLocaleIdentifier:(localeID))
tell formatter to setNumberStyle:(numberStyle)
return formatter
end getNumberFormatter
on join(listOfText, delimiter)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delimiter
set txt to listOfText as text
set AppleScript's text item delimiters to astid
return txt
end join
on fourIsMagic(n)
set n to n as number
if (n is 4) then return "Four is magic."
set formatter to getNumberFormatter("en_US", current application's NSNumberFormatterSpellOutStyle)
set nName to (formatter's stringFromNumber:(n)) as text
if (nName begins with "minus") then
set nName to "Negative " & text from word 2 to -1 of nName
else -- Crude ID-based capitalisation. Good enough for English number names.
set nName to character id ((id of character 1 of nName) - 32) & text 2 thru -1 of nName
end if
set output to {}
repeat until (n is 4)
set n to (count nName)
set lenName to (formatter's stringFromNumber:(n)) as text
set end of output to nName & " is " & lenName
set nName to lenName
end repeat
set end of output to "four is magic."
return join(output, ", ")
end fourIsMagic
local tests, output, n
set tests to {-19, 0, 4, 25, 32, 111, 1.234565789E+9}
set output to {}
repeat with n in tests
set end of output to fourIsMagic(n)
end repeat
return join(output, linefeed)
|
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
|
#Nemerle
|
Nemerle
|
public Multiply (a : int, b : int) : int // this is either a class or module method
{
def multiply(a, b) { return a * b } // this is a local function, can take advantage of type inference
return multiply(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
|
#NESL
|
NESL
|
function 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.)
|
#AWK
|
AWK
|
#!/usr/bin/awk -f
BEGIN {
if (p<1) {p = 1};
}
function diff(s, p) {
n = split(s, a, " ");
for (j = 1; j <= p; j++) {
for(i = 1; i <= n-j; i++) {
a[i] = a[i+1] - a[i];
}
}
s = "";
for (i = 1; i <= n-p; i++) s = s" "a[i];
return s;
}
{
print diff($0, p);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.