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/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related tasks
Draw a cuboid
write language name in 3D ASCII
| #Go | Go | package main
import (
"image"
"image/color"
"image/gif"
"log"
"math"
"os"
)
const (
width, height = 640, 640
offset = height / 2
fileName = "rotatingCube.gif"
)
var nodes = [][]float64{{-100, -100, -100}, {-100, -100, 100}, {-100, 100, -100}, {-100, 100, 100},
{100, -100, -100}, {100, -100, 100}, {100, 100, -100}, {100, 100, 100}}
var edges = [][]int{{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}
func main() {
var images []*image.Paletted
fgCol := color.RGBA{0xff, 0x00, 0xff, 0xff}
var palette = []color.Color{color.RGBA{0x00, 0x00, 0x00, 0xff}, fgCol}
var delays []int
imgFile, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer imgFile.Close()
rotateCube(math.Pi/4, math.Atan(math.Sqrt(2)))
var frame float64
for frame = 0; frame < 360; frame++ {
img := image.NewPaletted(image.Rect(0, 0, width, height), palette)
images = append(images, img)
delays = append(delays, 5)
for _, edge := range edges {
xy1 := nodes[edge[0]]
xy2 := nodes[edge[1]]
drawLine(int(xy1[0])+offset, int(xy1[1])+offset, int(xy2[0])+offset, int(xy2[1])+offset, img, fgCol)
}
rotateCube(math.Pi/180, 0)
}
if err := gif.EncodeAll(imgFile, &gif.GIF{Image: images, Delay: delays}); err != nil {
imgFile.Close()
log.Fatal(err)
}
}
func rotateCube(angleX, angleY float64) {
sinX := math.Sin(angleX)
cosX := math.Cos(angleX)
sinY := math.Sin(angleY)
cosY := math.Cos(angleY)
for _, node := range nodes {
x := node[0]
y := node[1]
z := node[2]
node[0] = x*cosX - z*sinX
node[2] = z*cosX + x*sinX
z = node[2]
node[1] = y*cosY - z*sinY
node[2] = z*cosY + y*sinY
}
}
func drawLine(x0, y0, x1, y1 int, img *image.Paletted, col color.RGBA) {
dx := abs(x1 - x0)
dy := abs(y1 - y0)
var sx, sy int = -1, -1
if x0 < x1 {
sx = 1
}
if y0 < y1 {
sy = 1
}
err := dx - dy
for {
img.Set(x0, y0, col)
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 > -dy {
err -= dy
x0 += sx
}
if e2 < dx {
err += dx
y0 += sy
}
}
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
} |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #MATLAB | MATLAB | a = rand;
b = rand(10,10);
scalar_matrix = a * b;
component_wise = b .* b; |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Arendelle | Arendelle | [ #j ,
[ #i ,
{ ( #x - 19 ) ^ 2 +
( #y - 14 ) ^ 2 < 125 , p
} r
] [ #i , l ] d
] |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #C.2B.2B | C++ | template <typename T>
void insert_after(Node<T>* N, T&& data)
{
auto node = new Node<T>{N, N->next, std::forward(data)};
if(N->next != nullptr)
N->next->prev = node;
N->next = node;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Clojure | Clojure | (defrecord Node [prev next data])
(defn new-node [prev next data]
(Node. (ref prev) (ref next) data))
(defn new-list [head tail]
(List. (ref head) (ref tail)))
(defn insert-between [node1 node2 new-node]
(dosync
(ref-set (:next node1) new-node)
(ref-set (:prev new-node) node1)
(ref-set (:next new-node) node2)
(ref-set (:prev node2) new-node)))
(set! *print-level* 1)
;; warning: depending on the value of *print-level*
;; this could cause a stack overflow when printing
(let [h (new-node nil nil :A)
t (new-node nil nil :B)]
(insert-between h t (new-node nil nil :C))
(new-list h t)) |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #AutoHotkey | AutoHotkey | LINK(L₁,1)→A
LINK(L₁+10,2)→B
LINK(L₁+50,3)→C
INSERT(A,B)
INSERT(A,C)
A→I
While I≠0
Disp VALUE(I)▶Dec,i
NEXT(I)→I
End
Disp "-----",i
B→I
While I≠0
Disp VALUE(I)▶Dec,i
PREV(I)→I
End |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Axe | Axe | LINK(L₁,1)→A
LINK(L₁+10,2)→B
LINK(L₁+50,3)→C
INSERT(A,B)
INSERT(A,C)
A→I
While I≠0
Disp VALUE(I)▶Dec,i
NEXT(I)→I
End
Disp "-----",i
B→I
While I≠0
Disp VALUE(I)▶Dec,i
PREV(I)→I
End |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #BBC_BASIC | BBC BASIC | DIM node{pPrev%, pNext%, iData%}
DIM a{} = node{}, b{} = node{}, c{} = node{}
a.pNext% = b{}
a.iData% = 123
b.pPrev% = a{}
b.iData% = 789
c.iData% = 456
PROCinsert(a{}, c{})
PRINT "Traverse forwards:"
pnode% = a{}
REPEAT
!(^node{}+4) = pnode%
PRINT node.iData%
pnode% = node.pNext%
UNTIL pnode% = 0
PRINT "Traverse backwards:"
pnode% = b{}
REPEAT
!(^node{}+4) = pnode%
PRINT node.iData%
pnode% = node.pPrev%
UNTIL pnode% = 0
END
DEF PROCinsert(here{}, new{})
LOCAL temp{} : DIM temp{} = node{}
new.pNext% = here.pNext%
new.pPrev% = here{}
!(^temp{}+4) = new.pNext%
temp.pPrev% = new{}
here.pNext% = new{}
ENDPROC
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Action.21 | Action! | DEFINE PTR="CARD"
TYPE ListNode=[
BYTE data
PTR prv,nxt] |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
Task
Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
Sort the balls in a way idiomatic to your language.
Check the sorted balls are in the order of the Dutch national flag.
C.f.
Dutch national flag problem
Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| #BaCon | BaCon | DECLARE color$[] = { "red", "white", "blue" }
DOTIMES 16
ball$ = APPEND$(ball$, 0, color$[RANDOM(3)] )
DONE
PRINT "Unsorted: ", ball$
PRINT " Sorted: ", REPLACE$(SORT$(REPLACE$(ball$, "blue", "z")), "z", "blue") |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
Task
Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
Sort the balls in a way idiomatic to your language.
Check the sorted balls are in the order of the Dutch national flag.
C.f.
Dutch national flag problem
Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| #BASIC256 | BASIC256 | arraybase 1
dim flag = {"Red","White","Blue"}
dim balls(9)
print "Random: |";
for i = 1 to 9
kolor = (rand * 3) + 1
balls[i] = flag[kolor]
print balls[i]; " |";
next i
print
print "Sorted: |";
for i = 1 to 3
kolor = flag[i]
for j = 1 to 9
if balls[j] = kolor then print balls[j]; " |";
next j
next i |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #AWK | AWK |
# syntax: GAWK -f DRAW_A_CUBOID.AWK [-v x=?] [-v y=?] [-v z=?]
# example: GAWK -f DRAW_A_CUBOID.AWK -v x=12 -v y=4 -v z=6
# converted from VBSCRIPT
BEGIN {
init_sides()
draw_cuboid(2,3,4)
draw_cuboid(1,1,1)
draw_cuboid(6,2,1)
exit (errors == 0) ? 0 : 1
}
function draw_cuboid(nx,ny,nz, esf,i,i_max,j,j_max,lx,ly,lz) {
esf = errors # errors so far
if (nx !~ /^[0-9]+$/ || nx <= 0) { error(nx,ny,nz,1) }
if (ny !~ /^[0-9]+$/ || ny <= 0) { error(nx,ny,nz,2) }
if (nz !~ /^[0-9]+$/ || nz <= 0) { error(nx,ny,nz,3) }
if (errors > esf) { return }
lx = x * nx
ly = y * ny
lz = z * nz
# define the array size
i_max = ly + lz
j_max = lx + ly
delete arr
printf("%s %s %s (%d rows x %d columns)\n",nx,ny,nz,i_max+1,j_max+1)
# draw lines
for (i=0; i<=nz-1; i++) { draw_line(lx,0,z*i,"-") }
for (i=0; i<=ny; i++) { draw_line(lx,y*i,lz+y*i,"-") }
for (i=0; i<=nx-1; i++) { draw_line(lz,x*i,0,"|") }
for (i=0; i<=ny; i++) { draw_line(lz,lx+y*i,y*i,"|") }
for (i=0; i<=nz-1; i++) { draw_line(ly,lx,z*i,"/") }
for (i=0; i<=nx; i++) { draw_line(ly,x*i,lz,"/") }
# output the cuboid
for (i=i_max; i>=0; i--) {
for (j=0; j<=j_max; j++) {
printf("%1s",arr[i,j])
}
printf("\n")
}
}
function draw_line(n,x,y,c, dx,dy,i,xi,yi) {
if (c == "-") { dx = 1 ; dy = 0 }
else if (c == "|") { dx = 0 ; dy = 1 }
else if (c == "/") { dx = 1 ; dy = 1 }
for (i=0; i<=n; i++) {
xi = x + i * dx
yi = y + i * dy
arr[yi,xi] = (arr[yi,xi] ~ /^ ?$/) ? c : "+"
}
}
function error(x,y,z,arg) {
printf("error: '%s,%s,%s' argument %d is invalid\n",x,y,z,arg)
errors++
}
function init_sides() {
# to change the defaults on the command line use: -v x=? -v y=? -v z=?
if (x+0 < 2) { x = 6 } # top
if (y+0 < 2) { y = 2 } # right
if (z+0 < 2) { z = 3 } # front
}
|
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Maxima | Maxima | /* Use :: for indirect assignment */
block([name: read("name?"), x: read("value?")], name :: x); |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #min | min | 42 "Enter a variable name" ask define |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #MUMPS | MUMPS | USER>KILL ;Clean up workspace
USER>WRITE ;show all variables and definitions
USER>READ "Enter a variable name: ",A
Enter a variable name: GIBBERISH
USER>SET @A=3.14159
USER>WRITE
A="GIBBERISH"
GIBBERISH=3.14159 |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Julia | Julia | using Gtk, Graphics
const can = @GtkCanvas()
const win = GtkWindow(can, "Draw a Pixel", 320, 240)
draw(can) do widget
ctx = getgc(can)
set_source_rgb(ctx, 255, 0, 0)
move_to(ctx, 100, 100)
line_to(ctx, 101,100)
stroke(ctx)
end
show(can)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
wait(cond)
|
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Kotlin | Kotlin | // Version 1.2.41
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val bbs = BasicBitmapStorage(320, 240)
with (bbs) {
fill(Color.white) // say
setPixel(100, 100, Color.red)
// check it worked
val c = getPixel(100, 100)
print("The color of the pixel at (100, 100) is ")
println(if (c == Color.red) "red" else "white")
}
} |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Phix | Phix | with javascript_semantics
procedure egyptian_division(integer dividend, divisor)
integer p2 = 1, dbl = divisor, ans = 0, accum = 0
sequence p2s = {}, dbls = {}, args
while dbl<=dividend do
p2s = append(p2s,p2)
dbls = append(dbls,dbl)
dbl += dbl
p2 += p2
end while
for i=length(p2s) to 1 by -1 do
if accum+dbls[i]<=dividend then
accum += dbls[i]
ans += p2s[i]
end if
end for
args = {dividend,divisor,ans,abs(accum-dividend)}
printf(1,"%d divided by %d is: %d remainder %d\n",args)
end procedure
egyptian_division(580,34)
|
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #Phix | Phix | with javascript_semantics
include mpfr.e
function egyptian(integer num, denom)
mpz n = mpz_init(num),
d = mpz_init(denom),
t = mpz_init()
sequence result = {}
while mpz_cmp_si(n,0)!=0 do
mpz_cdiv_q(t, d, n)
result = append(result,"1/"&mpz_get_str(t))
mpz_neg(d,d)
mpz_mod(n,d,n)
mpz_neg(d,d)
mpz_mul(d,d,t)
end while
{n,d} = mpz_free({n,d})
return result
end function
procedure efrac(integer num, denom)
string fraction = sprintf("%d/%d",{num,denom}),
prefix = ""
if num>=denom then
integer whole = floor(num/denom)
num -= whole*denom
prefix = sprintf("[%d] + ",whole)
end if
string e = join(egyptian(num, denom)," + ")
printf(1,"%s -> %s%s\n",{fraction,prefix,e})
end procedure
efrac(43,48)
efrac(5,121)
efrac(2014,59)
integer maxt = 0,
maxd = 0
string maxts = "",
maxds = "",
maxda = ""
for r=98 to 998 by 900 do -- (iterates just twice!)
sequence sieve = repeat(repeat(false,r+1),r) -- to eliminate duplicates
for n=1 to r do
for d=n+1 to r+1 do
if sieve[n][d]=false then
string term = sprintf("%d/%d",{n,d})
sequence terms = egyptian(n,d)
integer nterms = length(terms)
if nterms>maxt then
maxt = nterms
maxts = term
elsif nterms=maxt then
maxts &= ", " & term
end if
integer mlen = length(terms[$])-2
if mlen>maxd then
maxd = mlen
maxds = term
maxda = terms[$]
elsif mlen=maxd then
maxds &= ", " & term
end if
if n<r/2 then
for k=2 to 9999 do
if d*k > r+1 then exit end if
sieve[n*k][d*k] = true
end for
end if
end if
end for
end for
printf(1,"\nfor proper fractions with 1 to %d digits\n",{length(sprint(r))})
printf(1,"Largest number of terms is %d for %s\n",{maxt,maxts})
maxda = maxda[3..$] -- (strip the "1/")
maxda[6..-6]="..." -- (show only first/last 5 digits)
printf(1,"Largest size for denominator is %d digits (%s) for %s\n",{maxd,maxda,maxds})
end for
|
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Swift | Swift | import Darwin
func ethiopian(var #int1:Int, var #int2:Int) -> Int {
var lhs = [int1], rhs = [int2]
func isEven(#n:Int) -> Bool {return n % 2 == 0}
func double(#n:Int) -> Int {return n * 2}
func halve(#n:Int) -> Int {return n / 2}
while int1 != 1 {
lhs.append(halve(n: int1))
rhs.append(double(n: int2))
int1 = halve(n: int1)
int2 = double(n: int2)
}
var returnInt = 0
for (a,b) in zip(lhs, rhs) {
if (!isEven(n: a)) {
returnInt += b
}
}
return returnInt
}
println(ethiopian(int1: 17, int2: 34)) |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Rust | Rust |
fn main() {
struct ElementaryCA {
rule: u8,
state: u64,
}
impl ElementaryCA {
fn new(rule: u8) -> (u64, ElementaryCA) {
let out = ElementaryCA {
rule,
state: 1,
};
(out.state, out)
}
fn next(&mut self) -> u64 {
let mut next_state = 0u64;
let state = self.state;
for i in 0..64 {
next_state |= (((self.rule as u64)>>(7 & (state.rotate_left(1).rotate_right(i as u32)))) & 1)<<i;
}
self.state = next_state;
self.state
}
}
fn rep_u64(val: u64) -> String {
let mut out = String::new();
for i in (0..64).rev() {
if 1<<i & val != 0 {
out = out + "\u{2588}";
} else {
out = out + "-";
}
}
out
}
let (i, mut thirty) = ElementaryCA::new(154);
println!("{}",rep_u64(i));
for _ in 0..32 {
let s = thirty.next();
println!("{}", rep_u64(s));
}
}
|
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Scala | Scala | import java.awt._
import java.awt.event.ActionEvent
import javax.swing._
object ElementaryCellularAutomaton extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Elementary Cellular Automaton") {
class ElementaryCellularAutomaton extends JPanel {
private val dim = new Dimension(900, 450)
private val cells = Array.ofDim[Byte](dim.height, dim.width)
private var rule = 0
private def ruleSet =
Seq(30, 45, 50, 57, 62, 70, 73, 75, 86, 89, 90, 99, 101, 105, 109, 110, 124, 129, 133, 135, 137, 139, 141, 164, 170, 232)
override def paintComponent(gg: Graphics): Unit = {
def drawCa(g: Graphics2D): Unit = {
def rules(lhs: Int, mid: Int, rhs: Int) = {
val idx = lhs << 2 | mid << 1 | rhs
(ruleSet(rule) >> idx & 1).toByte
}
g.setColor(Color.black)
for (r <- 0 until cells.length - 1;
c <- 1 until cells(r).length - 1;
lhs = cells(r)(c - 1);
mid = cells(r)(c);
rhs = cells(r)(c + 1)) {
cells(r + 1)(c) = rules(lhs, mid, rhs) // next generation
if (cells(r)(c) == 1) g.fillRect(c, r, 1, 1)
}
}
def drawLegend(g: Graphics2D): Unit = {
val s = ruleSet(rule).toString
val sw = g.getFontMetrics.stringWidth(ruleSet(rule).toString)
g.setColor(Color.white)
g.fillRect(16, 5, 55, 30)
g.setColor(Color.darkGray)
g.drawString(s, 16 + (55 - sw) / 2, 30)
}
super.paintComponent(gg)
val g = gg.asInstanceOf[Graphics2D]
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawCa(g)
drawLegend(g)
}
new Timer(5000, (_: ActionEvent) => {
rule += 1
if (rule == ruleSet.length) rule = 0
repaint()
}).start()
cells(0)(dim.width / 2) = 1
setBackground(Color.white)
setFont(new Font("SansSerif", Font.BOLD, 28))
setPreferredSize(dim)
}
add(new ElementaryCellularAutomaton, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
})
} |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Wart | Wart | def (fact n)
if (n = 0)
1
(n * (fact n-1)) |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #PureBasic | PureBasic | NewMap RecData.s()
OpenWindow(0, 100, 200, 200, 100, "Echo Server", #PB_Window_SystemMenu | #PB_Window_MinimizeGadget )
InitNetwork()
CreateNetworkServer(1, 12321)
Repeat
Event = NetworkServerEvent()
ClientID = EventClient()
If Event = #PB_NetworkEvent_Connect ; When a new client has been connected...
AddMapElement(RecData(), Str(ClientID))
ElseIf Event = #PB_NetworkEvent_Data
*Buffer = AllocateMemory(20000)
count = ReceiveNetworkData(ClientID, *Buffer, 20000)
For i = 1 To count
RecData(Str(ClientID)) + Mid( PeekS(*Buffer, count), i , 1)
If Right( RecData(Str(ClientID)), 2) = #CRLF$
SendNetworkString (ClientID, RecData(Str(ClientID)))
Debug IPString(GetClientIP(ClientID)) + ":" + Str(GetClientPort(ClientID)) + " " + RecData(Str(ClientID))
RecData(Str(ClientID)) = ""
EndIf
Next
FreeMemory(*Buffer)
ElseIf Event = #PB_NetworkEvent_Disconnect ; When a client has closed the connection...
DeleteMapElement(RecData(), Str(ClientID))
EndIf
Event = WaitWindowEvent(10)
Until Event = #PB_Event_CloseWindow |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #Phix | Phix | with javascript_semantics
function count_eban(integer p10)
-- returns the count of eban numbers 1..power(10,p10)
integer n = p10-floor(p10/3),
p5 = floor(n/2),
p4 = floor((n+1)/2)
return power(5,p5)*power(4,p4)-1
end function
function eban(integer n)
-- returns true if n is an eban number (only fully tested to 10e9)
if n=0 then return false end if
while n do
integer thou = remainder(n,1000)
if floor(thou/100)!=0 then return false end if
if not find(floor(thou/10),{0,3,4,5,6}) then return false end if
if not find(remainder(thou,10),{0,2,4,6}) then return false end if
n = floor(n/1000)
end while
return true
end function
sequence s = {}
for i=0 to 1000 do
if eban(i) then s = append(s,sprint(i)) end if
end for
printf(1,"eban to 1000 : %s\n\n",{join(shorten(s,"items",8))})
s = {}
for i=1000 to 4000 do
if eban(i) then s = append(s,sprint(i)) end if
end for
printf(1,"eban 1000..4000 : %s\n\n",{join(shorten(s,"items",4))})
atom t0 = time()
for i=0 to 21 do
printf(1,"count_eban(10^%d) : %,d\n",{i,count_eban(i)})
end for
?elapsed(time()-t0)
|
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related tasks
Draw a cuboid
write language name in 3D ASCII
| #Haskell | Haskell | {-# LANGUAGE RecursiveDo #-}
import Reflex.Dom
import Data.Map as DM (Map, lookup, insert, empty, fromList)
import Data.Matrix
import Data.Time.Clock
import Control.Monad.Trans
size = 500
updateFrequency = 0.2
rotationStep = pi/10
data Color = Red | Green | Blue | Yellow | Orange | Purple | Black deriving (Show,Eq,Ord,Enum)
zRot :: Float -> Matrix Float
zRot rotation =
let c = cos rotation
s = sin rotation
in fromLists [[ c, s, 0, 0 ]
,[-s, c, 0, 0 ]
,[ 0, 0, 1, 0 ]
,[ 0, 0, 0, 1 ]
]
xRot :: Float -> Matrix Float
xRot rotation =
let c = cos rotation
s = sin rotation
in fromLists [[ 1, 0, 0, 0 ]
,[ 0, c, s, 0 ]
,[ 0, -s, c, 0 ]
,[ 0, 0, 0, 1 ]
]
yRot :: Float -> Matrix Float
yRot rotation =
let c = cos rotation
s = sin rotation
in fromLists [[ c, 0, -s, 0 ]
,[ 0, 1, 0, 0 ]
,[ s, 0, c, 0 ]
,[ 0, 0, 0, 1 ]
]
translation :: (Float,Float,Float) -> Matrix Float
translation (x,y,z) =
fromLists [[ 1, 0, 0, 0 ]
,[ 0, 1, 0, 0 ]
,[ 0, 0, 1, 0 ]
,[ x, y, z, 1 ]
]
scale :: Float -> Matrix Float
scale s =
fromLists [[ s, 0, 0, 0 ]
,[ 0, s, 0, 0 ]
,[ 0, 0, s, 0 ]
,[ 0, 0, 0, 1 ]
]
-- perspective transformation;
perspective :: Matrix Float
perspective =
fromLists [[ 1, 0, 0, 0 ]
,[ 0, 1, 0, 0 ]
,[ 0, 0, 1, 1 ]
,[ 0, 0, 1, 1 ] ]
transformPoints :: Matrix Float -> Matrix Float -> [(Float,Float)]
transformPoints transform points =
let result4d = points `multStd2` transform
result2d = (\[x,y,z,w] -> (x/w,y/w)) <$> toLists result4d
in result2d
showRectangle :: MonadWidget t m => Float -> Float -> Float -> Float -> Color -> Dynamic t (Matrix Float) -> m ()
showRectangle x0 y0 x1 y1 faceColor dFaceView = do
let points = fromLists [[x0,y0,0,1],[x0,y1,0,1],[x1,y1,0,1],[x1,y0,0,1]]
pointsToString = concatMap (\(x,y) -> show x ++ ", " ++ show y ++ " ")
dAttrs <- mapDyn (\fvk -> DM.fromList [ ("fill", show faceColor)
, ("points", pointsToString (transformPoints fvk points))
] ) dFaceView
elDynAttrSVG "polygon" dAttrs $ return ()
showUnitSquare :: MonadWidget t m => Color -> Float -> Dynamic t (Matrix Float) -> m ()
showUnitSquare faceColor margin dFaceView =
showRectangle margin margin (1.0 - margin) (1.0 - margin) faceColor dFaceView
-- show colored square on top of black square for outline effect
showFace :: MonadWidget t m => Color -> Dynamic t (Matrix Float) -> m ()
showFace faceColor dFaceView = do
showUnitSquare Black 0 dFaceView
showUnitSquare faceColor 0.03 dFaceView
facingCamera :: [Float] -> Matrix Float -> Bool
facingCamera viewPoint modelTransform =
let cross [x0,y0,z0] [x1,y1,z1] = [y0*z1-z0*y1, z0*x1-x0*z1, x0*y1-y0*x1 ]
dot v0 v1 = sum $ zipWith (*) v0 v1
vMinus = zipWith (-)
untransformedPoints = fromLists [ [0,0,0,1] -- lower left
, [1,0,0,1] -- lower right
, [0,1,0,1] ] -- upper left
transformedPoints = toLists $ untransformedPoints `multStd2` modelTransform
pt00 = take 3 $ head transformedPoints -- transformed lower left
pt10 = take 3 $ transformedPoints !! 1 -- transformed upper right
pt01 = take 3 $ transformedPoints !! 2 -- transformed upper left
tVec_10_00 = pt10 `vMinus` pt00 -- lower right to lower left
tVec_01_00 = pt01 `vMinus` pt00 -- upper left to lower left
perpendicular = tVec_10_00 `cross` tVec_01_00 -- perpendicular to face
cameraToPlane = pt00 `vMinus` viewPoint -- line of sight to face
-- Perpendicular points away from surface;
-- Camera vector points towards surface
-- Opposed vectors means that face will be visible.
in cameraToPlane `dot` perpendicular < 0
faceView :: Matrix Float -> Matrix Float -> (Bool, Matrix Float)
faceView modelOrientation faceOrientation =
let modelTransform = translation (-1/2,-1/2,1/2) -- unit square to origin + z offset
`multStd2` faceOrientation -- orientation specific to each face
`multStd2` scale (1/2) -- shrink cube to fit in view.
`multStd2` modelOrientation -- position the entire cube
isFacingCamera = facingCamera [0,0,-1] modelTransform -- backface elimination
-- combine to get single transform from 2d face to 2d display
viewTransform = modelTransform
`multStd2` perspective
`multStd2` scale size -- scale up to svg box scale
`multStd2` translation (size/2, size/2, 0) -- move to center of svg box
in (isFacingCamera, viewTransform)
updateFaceViews :: Matrix Float -> Map Color (Matrix Float) -> (Color, Matrix Float) -> Map Color (Matrix Float)
updateFaceViews modelOrientation prevCollection (faceColor, faceOrientation) =
let (isVisible, newFaceView) = faceView modelOrientation faceOrientation
in if isVisible
then insert faceColor newFaceView prevCollection
else prevCollection
faceViews :: Matrix Float -> Map Color (Matrix Float)
faceViews modelOrientation =
foldl (updateFaceViews modelOrientation) empty
[ (Purple , xRot (0.0) )
, (Yellow , xRot (pi/2) )
, (Red , yRot (pi/2) )
, (Green , xRot (-pi/2) )
, (Blue , yRot (-pi/2) )
, (Orange , xRot (pi) )
]
viewModel :: MonadWidget t m => Dynamic t (Matrix Float) -> m ()
viewModel modelOrientation = do
faceMap <- mapDyn faceViews modelOrientation
listWithKey faceMap showFace
return ()
view :: MonadWidget t m => Dynamic t (Matrix Float) -> m ()
view modelOrientation = do
el "h1" $ text "Rotating Cube"
elDynAttrSVG "svg"
(constDyn $ DM.fromList [ ("width", show size), ("height", show size) ])
$ viewModel modelOrientation
main = mainWidget $ do
let initialOrientation = xRot (pi/4) `multStd2` zRot (atan(1/sqrt(2)))
update _ modelOrientation = modelOrientation `multStd2` (yRot (rotationStep) )
tick <- tickLossy updateFrequency =<< liftIO getCurrentTime
rec
view modelOrientation
modelOrientation <- foldDyn update initialOrientation tick
return ()
-- At end because of Rosetta Code handling of unmatched quotes.
elDynAttrSVG a2 a3 a4 = do
elDynAttrNS' (Just "http://www.w3.org/2000/svg") a2 a3 a4
return () |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #Maxima | Maxima | a: matrix([1, 2], [3, 4]);
b: matrix([2, 4], [3, 1]);
a * b;
a / b;
a + b;
a - b;
a^3;
a^b; /* won't work */
fullmapl("^", a, b);
sin(a); |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #Nim | Nim | import math, strutils
type Matrix[height, width: static Positive; T: SomeNumber] = array[height, array[width, T]]
####################################################################################################
proc `$`(m: Matrix): string =
for i, row in m:
var line = "["
for j, val in row:
line.addSep(" ", 1)
line.add($val)
line.add("]\n")
result.add(line)
####################################################################################################
# Templates.
template elementWise(m1, m2: Matrix; op: proc(v1, v2: m1.T): auto): untyped =
var result: Matrix[m1.height, m1.width, m1.T]
for i in 0..<m1.height:
for j in 0..<m1.width:
result[i][j] = op(m1[i][j], m2[i][j])
result
template scalarOp(m: Matrix; val: SomeNumber; op: proc(v1, v2: SomeNumber): auto): untyped =
var result: Matrix[m.height, m.width, m.T]
for i in 0..<m.height:
for j in 0..<m.width:
result[i][j] = op(m[i][j], val)
result
template scalarOp(val: SomeNumber; m: Matrix; op: proc(v1, v2: SomeNumber): auto): untyped =
var result: Matrix[m.height, m.width, m.T]
for i in 0..<m.height:
for j in 0..<m.width:
result[i][j] = op(val, m[i][j])
result
####################################################################################################
# Access functions.
func `[]`(m: Matrix; i, j: int): m.T =
m[i][j]
func `[]=`(m: var Matrix; i, j: int; val: SomeNumber) =
m[i][j] = val
####################################################################################################
# Elementwise operations.
func `+`(m1, m2: Matrix): Matrix =
elementWise(m1, m2, `+`)
func `-`(m1, m2: Matrix): Matrix =
elementWise(m1, m2, `-`)
func `*`(m1, m2: Matrix): Matrix =
elementWise(m1, m2, `*`)
func `div`(m1, m2: Matrix): Matrix =
elementWise(m1, m2, `div`)
func `mod`(m1, m2: Matrix): Matrix =
elementWise(m1, m2, `mod`)
func `/`(m1, m2: Matrix): Matrix =
elementWise(m1, m2, `/`)
func `^`(m1, m2: Matrix): Matrix =
# Cannot use "elementWise" template as it requires both operator arguments
# to be of type "m1.T" (and second argument of `^` is "Natural", not "int").
for i in 0..<m1.height:
for j in 0..<m1.width:
result[i][j] = m1[i][j] ^ m2[i][j]
func pow(m1, m2: Matrix): Matrix =
elementWise(m1, m2, pow)
####################################################################################################
# Matrix-scalar and scalar-matrix operations.
func `+`(m: Matrix; val: SomeNumber): Matrix =
scalarOp(m, val, `+`)
func `+`(val: SomeNumber; m: Matrix): Matrix =
scalarOp(val, m, `+`)
func `-`(m: Matrix; val: SomeNumber): Matrix =
scalarOp(m, val, `-`)
func `-`(val: SomeNumber; m: Matrix): Matrix =
scalarOp(val, m, `-`)
func `*`(m: Matrix; val: SomeNumber): Matrix =
scalarOp(m, val, `*`)
func `*`(val: SomeNumber; m: Matrix): Matrix =
scalarOp(val, m, `*`)
func `div`(m: Matrix; val: SomeNumber): Matrix =
scalarOp(m, val, `div`)
func `div`(val: SomeNumber; m: Matrix): Matrix =
scalarOp(val, m, `div`)
func `mod`(m: Matrix; val: m.T): Matrix =
scalarOp(m, val, `mod`)
func `mod`(val: SomeNumber; m: Matrix): Matrix =
scalarOp(val, m, `mod`)
proc `/`(m: Matrix; val: SomeNumber): Matrix =
scalarOp(m, val, `/`)
func `/`(val: SomeNumber; m: Matrix): Matrix =
scalarOp(val, m, `/`)
func `^`(m: Matrix; val: Natural): Matrix =
# Cannot use "elementWise" template as it requires both operator arguments
# to be of type "m.T" (and second argument of `^` is "Natural", not "int").
for i in 0..<m.height:
for j in 0..<m.width:
result[i][j] = m[i][j] ^ val
func `^`(val: Natural; m: Matrix): Matrix =
# Cannot use "elementWise" template as it requires both operator arguments
# to be of type "m.T" (and second argument of `^` is "Natural", not "int").
for i in 0..<m.height:
for j in 0..<m.width:
result[i][j] = val ^ m[i][j]
func pow(m: Matrix; val: SomeNumber): Matrix =
scalarOp(m, val, pow)
func `pow`(val: SomeNumber; m: Matrix): Matrix =
scalarOp(val, m, `pow`)
#———————————————————————————————————————————————————————————————————————————————————————————————————
# Operations on integer matrices.
let mint1: Matrix[2, 2, int] = [[1, 2], [3, 4]]
let mint2: Matrix[2, 2, int] = [[2, 1], [4, 2]]
echo "Integer matrices"
echo "----------------\n"
echo "m1:"
echo mint1
echo "m2:"
echo mint2
echo "m1 + m2"
echo mint1 + mint2
echo "m1 - m2"
echo mint1 - mint2
echo "m1 * m2"
echo mint1 * mint2
echo "m1 div m2"
echo mint1 div mint2
echo "m1 mod m2"
echo mint1 mod mint2
echo "m1^m2"
echo mint1^mint2
echo "2 * m1"
echo 2 * mint1
echo "m1 * 2"
echo mint1 * 2
echo "m1^2"
echo mint1 ^ 2
echo "2^m1"
echo 2 ^ mint1
# Operations on float matrices.
let mfloat1: Matrix[2, 3, float] = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
let mfloat2: Matrix[2, 3, float] = [[2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]
echo "\nFloat matrices"
echo "--------------\n"
echo "m1"
echo mfloat1
echo "m2"
echo mfloat2
echo "m1 + m2"
echo mfloat1 + mfloat2
echo "m1 - m2"
echo mfloat1 - mfloat2
echo "m1 * m2"
echo mfloat1 * mfloat2
echo "m1 / m2"
echo mfloat1 / mfloat2
echo "pow(m1, m2)"
echo pow(mfloat1, mfloat2)
echo "pow(m1, 2.0)"
echo pow(mfloat1, 2.0)
echo "pow(2.0, m1)"
echo pow(2.0, mfloat1) |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #ATS | ATS |
(*
** Solution to Draw_a_sphere.dats
*)
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
#include
"share/HATS/atslib_staload_libats_libc.hats" // for libc
//
(* ****** ****** *)
extern
fun
Draw_a_sphere
(
R: double, k: double, ambient: double
) : void // end of [Draw_a_sphere]
(* ****** ****** *)
implement
Draw_a_sphere
(
R: double, k: double, ambient: double
) = let
fun normalize(v0: double, v1: double, v2: double): (double, double, double) = let
val len = sqrt(v0*v0+v1*v1+v2*v2)
in
(v0/len, v1/len, v2/len)
end // end of [normalize]
fun dot(v0: double, v1: double, v2: double, x0: double, x1: double, x2: double): double = let
val d = v0*x0+v1*x1+v2*x2
val sgn = gcompare_val_val<double> (d, 0.0)
in
if sgn < 0 then ~d else 0.0
end // end of [dot]
fun print_char(i: int): void =
if i = 0 then print!(".") else
if i = 1 then print!(":") else
if i = 2 then print!("!") else
if i = 3 then print!("*") else
if i = 4 then print!("o") else
if i = 5 then print!("e") else
if i = 6 then print!("&") else
if i = 7 then print!("#") else
if i = 8 then print!("%") else
if i = 9 then print!("@") else print!(" ")
val i_start = floor(~R)
val i_end = ceil(R)
val j_start = floor(~2 * R)
val j_end = ceil(2 * R)
val (l0, l1, l2) = normalize(30.0, 30.0, ~50.0)
fun loopj(j: int, j_end: int, x: double): void = let
val y = j / 2.0 + 0.5;
val sgn = gcompare_val_val<double> (x*x + y*y, R*R)
val (v0, v1, v2) = normalize(x, y, sqrt(R*R - x*x - y*y))
val b = pow(dot(l0, l1, l2, v0, v1, v2), k) + ambient
val intensity = 9.0 - 9.0*b
val sgn2 = gcompare_val_val<double> (intensity, 0.0)
val sgn3 = gcompare_val_val<double> (intensity, 9.0)
in
( if sgn > 0 then print_char(10) else
if sgn2 < 0 then print_char(0) else
if sgn3 >= 0 then print_char(8) else
print_char(g0float2int(intensity));
if j < j_end then loopj(j+1, j_end, x)
)
end // end of [loopj]
fun loopi(i: int, i_end: int, j: int, j_end: int): void = let
val x = i + 0.5
val () = loopj(j, j_end, x)
val () = println!()
in
if i < i_end then loopi(i+1, i_end, j, j_end)
end // end of [loopi]
in
loopi(g0float2int(i_start), g0float2int(i_end), g0float2int(j_start), g0float2int(j_end))
end
(* ****** ****** *)
implement
main0() = () where
{
val () = DrawSphere(20.0, 4.0, .1)
val () = DrawSphere(10.0, 2.0, .4)
} (* end of [main0] *)
(* ****** ****** *)
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Common_Lisp | Common Lisp | import std.stdio;
struct Node(T) {
T data;
typeof(this)* prev, next;
}
/// If prev is null, prev gets to point to a new node.
void insertAfter(T)(ref Node!T* prev, T item) pure nothrow {
if (prev) {
auto newNode = new Node!T(item, prev, prev.next);
prev.next = newNode;
if (newNode.next)
newNode.next.prev = newNode;
} else
prev = new Node!T(item);
}
void show(T)(Node!T* list) {
while (list) {
write(list.data, " ");
list = list.next;
}
writeln;
}
void main() {
Node!(string)* list;
insertAfter(list, "A");
list.show;
insertAfter(list, "B");
list.show;
insertAfter(list, "C");
list.show;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #D | D | import std.stdio;
struct Node(T) {
T data;
typeof(this)* prev, next;
}
/// If prev is null, prev gets to point to a new node.
void insertAfter(T)(ref Node!T* prev, T item) pure nothrow {
if (prev) {
auto newNode = new Node!T(item, prev, prev.next);
prev.next = newNode;
if (newNode.next)
newNode.next.prev = newNode;
} else
prev = new Node!T(item);
}
void show(T)(Node!T* list) {
while (list) {
write(list.data, " ");
list = list.next;
}
writeln;
}
void main() {
Node!(string)* list;
insertAfter(list, "A");
list.show;
insertAfter(list, "B");
list.show;
insertAfter(list, "C");
list.show;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C | C | // A doubly linked list of strings;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct sListEntry {
const char *value;
struct sListEntry *next;
struct sListEntry *prev;
} *ListEntry, *LinkedList;
typedef struct sListIterator{
ListEntry link;
LinkedList head;
} *LIterator;
LinkedList NewList() {
ListEntry le = malloc(sizeof(struct sListEntry));
if (le) {
le->value = NULL;
le->next = le->prev = NULL;
}
return le;
}
int LL_Append(LinkedList ll, const char *newVal)
{
ListEntry le = malloc(sizeof(struct sListEntry));
if (le) {
le->value = strdup(newVal);
le->prev = ll->prev;
le->next = NULL;
if (le->prev)
le->prev->next = le;
else
ll->next = le;
ll->prev = le;
}
return (le!= NULL);
}
int LI_Insert(LIterator iter, const char *newVal)
{
ListEntry crnt = iter->link;
ListEntry le = malloc(sizeof(struct sListEntry));
if (le) {
le->value = strdup(newVal);
if ( crnt == iter->head) {
le->prev = NULL;
le->next = crnt->next;
crnt->next = le;
if (le->next)
le->next->prev = le;
else
crnt->prev = le;
}
else {
le->prev = ( crnt == NULL)? iter->head->prev : crnt->prev;
le->next = crnt;
if (le->prev)
le->prev->next = le;
else
iter->head->next = le;
if (crnt)
crnt->prev = le;
else
iter->head->prev = le;
}
}
return (le!= NULL);
}
LIterator LL_GetIterator(LinkedList ll )
{
LIterator liter = malloc(sizeof(struct sListIterator));
liter->head = ll;
liter->link = ll;
return liter;
}
#define LLI_Delete( iter ) \
{free(iter); \
iter = NULL;}
int LLI_AtEnd(LIterator iter)
{
return iter->link == NULL;
}
const char *LLI_Value(LIterator iter)
{
return (iter->link)? iter->link->value: NULL;
}
int LLI_Next(LIterator iter)
{
if (iter->link) iter->link = iter->link->next;
return(iter->link != NULL);
}
int LLI_Prev(LIterator iter)
{
if (iter->link) iter->link = iter->link->prev;
return(iter->link != NULL);
}
int main()
{
static const char *contents[] = {"Read", "Orage", "Yeller",
"Glean", "Blew", "Burple"};
int ix;
LinkedList ll = NewList(); //new linked list
LIterator iter;
for (ix=0; ix<6; ix++) //insert contents
LL_Append(ll, contents[ix]);
iter = LL_GetIterator(ll); //get an iterator
printf("forward\n");
while(LLI_Next(iter)) //iterate forward
printf("value=%s\n", LLI_Value(iter));
LLI_Delete(iter); //delete iterator
printf("\nreverse\n");
iter = LL_GetIterator(ll);
while(LLI_Prev(iter)) //iterate reverse
printf("value=%s\n", LLI_Value(iter));
LLI_Delete(iter);
//uhhh-- delete list??
return 0;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ada | Ada | type Link;
type Link_Access is access Link;
type Link is record
Next : Link_Access := null;
Prev : Link_Access := null;
Data : Integer;
end record; |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be queued #
END CO
MODE OBJLINK = STRUCT(
REF OBJLINK next,
REF OBJLINK prev,
OBJVALUE value # ... etc. required #
);
PROC obj link new = REF OBJLINK: HEAP OBJLINK;
PROC obj link free = (REF OBJLINK free)VOID:
prev OF free := next OF free := obj queue empty # give the garbage collector a big hint # |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ALGOL_W | ALGOL W | % record type to hold an element of a doubly linked list of integers %
record DListIElement ( reference(DListIElement) prev
; integer iValue
; reference(DListIElement) next
);
% additional record types would be required for other element types % |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
Task
Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
Sort the balls in a way idiomatic to your language.
Check the sorted balls are in the order of the Dutch national flag.
C.f.
Dutch national flag problem
Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
nBalls% = 12
DIM Balls$(nBalls%-1), Weight%(nBalls%-1), DutchFlag$(2)
DutchFlag$() = "Red ", "White ", "Blue "
REM. Generate random list of balls, ensuring not sorted:
REPEAT
prev% = 0 : sorted% = TRUE
FOR ball% = 0 TO nBalls%-1
index% = RND(3) - 1
Balls$(ball%) = DutchFlag$(index%)
IF index% < prev% THEN sorted% = FALSE
prev% = index%
NEXT
UNTIL NOT sorted%
PRINT "Random list: " SUM(Balls$())
REM. Assign Dutch Flag weightings to ball colours:
DutchFlag$ = SUM(DutchFlag$())
FOR ball% = 0 TO nBalls%-1
Weight%(ball%) = INSTR(DutchFlag$, Balls$(ball%))
NEXT
REM. Sort into Dutch Flag colour sequence:
C% = nBalls%
CALL Sort%, Weight%(0), Balls$(0)
PRINT "Sorted list: " SUM(Balls$())
REM Final check:
prev% = 0 : sorted% = TRUE
FOR ball% = 0 TO nBalls%-1
weight% = INSTR(DutchFlag$, Balls$(ball%))
IF weight% < prev% THEN sorted% = FALSE
prev% = weight%
NEXT
IF NOT sorted% PRINT "Error: Balls are not in correct order!" |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
Task
Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
Sort the balls in a way idiomatic to your language.
Check the sorted balls are in the order of the Dutch national flag.
C.f.
Dutch national flag problem
Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| #C | C | #include <stdio.h> //printf()
#include <stdlib.h> //srand(), rand(), RAND_MAX, qsort()
#include <stdbool.h> //true, false
#include <time.h> //time()
#define NUMBALLS 5 //NUMBALLS>1
int compar(const void *a, const void *b){
char c1=*(const char*)a, c2=*(const char*)b; //first cast void* to char*, then dereference
return c1-c2;
}
_Bool issorted(char *balls){
int i,state;
state=0;
for(i=0;i<NUMBALLS;i++){
if(balls[i]<state)return false;
if(balls[i]>state)state=balls[i];
}
return true;
}
void printout(char *balls){
int i;
char str[NUMBALLS+1];
for(i=0;i<NUMBALLS;i++)str[i]=balls[i]==0?'r':balls[i]==1?'w':'b';
printf("%s\n",str);
}
int main(void) {
char balls[NUMBALLS]; //0=r, 1=w, 2=b
int i;
srand(time(NULL)); //not a good seed but good enough for the example
rand(); //rand() always starts with the same values for certain seeds, making
// testing pretty irritating
// Generate balls
for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3;
while(issorted(balls)){ //enforce that we start with non-sorted balls
printf("Accidentally still sorted: ");
printout(balls);
for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3;
}
printf("Non-sorted: ");
printout(balls);
qsort(balls,NUMBALLS,sizeof(char),compar); //sort them using quicksort (stdlib)
if(issorted(balls)){ //unnecessary check but task enforces it
printf("Sorted: ");
printout(balls);
} else {
printf("Sort failed: ");
printout(balls);
}
return 0;
} |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #BBC_BASIC | BBC BASIC | ORIGIN 100, 100
PROCcuboid(200, 300, 400)
END
DEF PROCcuboid(x, y, z)
MOVE 0, 0 : MOVE 0, y
GCOL 1 : PLOT 117, x, y
GCOL 2 : PLOT 117, x + z * 0.4, y + z * 0.4
GCOL 4 : PLOT 117, x + z * 0.4, z * 0.4
ENDPROC
|
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Nanoquery | Nanoquery | print "Enter a variable name: "
name = input()
print name + " = "
exec(name + " = 42")
exec("println " + name) |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Nim | Nim | import tables
var
theVar: int = 5
varMap = initTable[string, pointer]()
proc ptrToInt(p: pointer): int =
result = cast[ptr int](p)[]
proc main() =
write(stdout, "Enter a var name: ")
let sVar = readLine(stdin)
varMap[$svar] = theVar.addr
echo "Variable ", sVar, " is ", ptrToInt(varMap[$sVar])
when isMainModule:
main() |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Octave | Octave | varname = input ("Enter variable name: ", "s");
value = input ("Enter value: ", "s");
eval([varname,"=",value]); |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Lambdatalk | Lambdatalk |
1) html/css
{div {@ style="position:relative;
left:0; top:0; width:320px; height:240px;
border:1px solid #000;"}
{div {@ style="position:absolute; left:100px; top:100px;
width:1px; height:1px; background:#f00; border:0;"}}}
2) svg
{svg {@ width="320" height="240"
style="border:1px solid #000;"}
{rect {@ x="100" y="100" width="1" height="1"
style="fill:#f00; stroke-width:0; stroke:#f00;"}}}
3) canvas
{canvas {@ id="canvas" width="320" height="240"
style="border:1px solid #000;"}}
{script
var canvas_pixel = function(x, y, canvas) {
var ctx = document.getElementById( canvas )
.getContext( "2d" );
ctx.fillStyle = "#f00";
ctx.fillRect(x,y,1,1);
};
setTimeout( canvas_pixel, 1, 100, 100, "canvas" )
}
|
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #PicoLisp | PicoLisp | (seed (in "/dev/urandom" (rd 8)))
(de divmod (Dend Disor)
(cons (/ Dend Disor) (% Dend Disor)) )
(de egyptian (Dend Disor)
(let
(P 0
D Disor
S
(make
(while (>= Dend (setq @@ (+ D D)))
(yoke
(cons
(** 2 (swap 'P (inc P)))
(swap 'D @@) ) ) ) )
P (** 2 P) )
(mapc
'((L)
(and
(>= Dend (+ D (cdr L)))
(inc 'P (car L))
(inc 'D (cdr L)) ) )
S )
(cons P (abs (- Dend D))) ) )
(for N 1000
(let (A (rand 1 1000) B (rand 1 A))
(test (divmod A B) (egyptian A B)) ) )
(println (egyptian 580 34)) |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Prolog | Prolog | egyptian_divide(Dividend, Divisor, Quotient, Remainder):-
powers2_multiples(Dividend, [1], Powers, [Divisor], Multiples),
accumulate(Dividend, Powers, Multiples, 0, Quotient, 0, Acc),
Remainder is Dividend - Acc.
powers2_multiples(Dividend, Powers, Powers, Multiples, Multiples):-
Multiples = [M|_],
2 * M > Dividend,
!.
powers2_multiples(Dividend, [Power|P], Powers, [Multiple|M], Multiples):-
Power2 is 2 * Power,
Multiple2 is 2 * Multiple,
powers2_multiples(Dividend, [Power2,Power|P], Powers,
[Multiple2, Multiple|M], Multiples).
accumulate(_, [], [], Ans, Ans, Acc, Acc):-!.
accumulate(Dividend, [P|Powers], [M|Multiples], Ans1, Answer, Acc1, Acc):-
Acc1 + M =< Dividend,
!,
Acc2 is Acc1 + M,
Ans2 is Ans1 + P,
accumulate(Dividend, Powers, Multiples, Ans2, Answer, Acc2, Acc).
accumulate(Dividend, [_|Powers], [_|Multiples], Ans1, Answer, Acc1, Acc):-
accumulate(Dividend, Powers, Multiples, Ans1, Answer, Acc1, Acc).
test_egyptian_divide(Dividend, Divisor):-
egyptian_divide(Dividend, Divisor, Quotient, Remainder),
writef('%w / %w = %w, remainder = %w\n', [Dividend, Divisor,
Quotient, Remainder]).
main:-
test_egyptian_divide(580, 34). |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #Prolog | Prolog | count_digits(Number, Count):-
atom_number(A, Number),
atom_length(A, Count).
integer_to_atom(Number, Atom):-
atom_number(A, Number),
atom_length(A, Count),
(Count =< 20 ->
Atom = A
;
sub_atom(A, 0, 10, _, A1),
P is Count - 10,
sub_atom(A, P, 10, _, A2),
atom_concat(A1, '...', A3),
atom_concat(A3, A2, Atom)
).
egyptian(0, _, []):- !.
egyptian(X, Y, [Z|E]):-
Z is (Y + X - 1)//X,
X1 is -Y mod X,
Y1 is Y * Z,
egyptian(X1, Y1, E).
print_egyptian([]):- !.
print_egyptian([N|List]):-
integer_to_atom(N, A),
write(1/A),
(List = [] -> true; write(' + ')),
print_egyptian(List).
print_egyptian(X, Y):-
writef('Egyptian fraction for %t/%t: ', [X, Y]),
(X > Y ->
N is X//Y,
writef('[%t] ', [N]),
X1 is X mod Y
;
X1 = X
),
egyptian(X1, Y, E),
print_egyptian(E),
nl.
max_terms_and_denominator1(D, Max_terms, Max_denom, Max_terms1, Max_denom1):-
max_terms_and_denominator1(D, 1, Max_terms, Max_denom, Max_terms1, Max_denom1).
max_terms_and_denominator1(D, D, Max_terms, Max_denom, Max_terms, Max_denom):- !.
max_terms_and_denominator1(D, N, Max_terms, Max_denom, Max_terms1, Max_denom1):-
Max_terms1 = f(_, _, _, Len1),
Max_denom1 = f(_, _, _, Max1),
egyptian(N, D, E),
length(E, Len),
last(E, Max),
(Len > Len1 ->
Max_terms2 = f(N, D, E, Len)
;
Max_terms2 = Max_terms1
),
(Max > Max1 ->
Max_denom2 = f(N, D, E, Max)
;
Max_denom2 = Max_denom1
),
N1 is N + 1,
max_terms_and_denominator1(D, N1, Max_terms, Max_denom, Max_terms2, Max_denom2).
max_terms_and_denominator(N, Max_terms, Max_denom):-
max_terms_and_denominator(N, 1, Max_terms, Max_denom, f(0, 0, [], 0),
f(0, 0, [], 0)).
max_terms_and_denominator(N, N, Max_terms, Max_denom, Max_terms, Max_denom):-!.
max_terms_and_denominator(N, N1, Max_terms, Max_denom, Max_terms1, Max_denom1):-
max_terms_and_denominator1(N1, Max_terms2, Max_denom2, Max_terms1, Max_denom1),
N2 is N1 + 1,
max_terms_and_denominator(N, N2, Max_terms, Max_denom, Max_terms2, Max_denom2).
show_max_terms_and_denominator(N):-
writef('Proper fractions with most terms and largest denominator, limit = %t:\n', [N]),
max_terms_and_denominator(N, f(N_max_terms, D_max_terms, E_max_terms, Len),
f(N_max_denom, D_max_denom, E_max_denom, Max)),
writef('Most terms (%t): %t/%t = ', [Len, N_max_terms, D_max_terms]),
print_egyptian(E_max_terms),
nl,
count_digits(Max, Digits),
writef('Largest denominator (%t digits): %t/%t = ', [Digits, N_max_denom, D_max_denom]),
print_egyptian(E_max_denom),
nl.
main:-
print_egyptian(43, 48),
print_egyptian(5, 121),
print_egyptian(2014, 59),
nl,
show_max_terms_and_denominator(100),
nl,
show_max_terms_and_denominator(1000). |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Tcl | Tcl | # This is how to declare functions - the mathematical entities - as opposed to procedures
proc function {name arguments body} {
uplevel 1 [list proc tcl::mathfunc::$name $arguments [list expr $body]]
}
function double n {$n * 2}
function halve n {$n / 2}
function even n {($n & 1) == 0}
function mult {a b} {
$a < 1 ? 0 :
even($a) ? [logmult STRUCK] + mult(halve($a), double($b))
: [logmult KEPT] + mult(halve($a), double($b)) + $b
}
# Wrapper to set up the logging
proc ethiopianMultiply {a b {tutor false}} {
if {$tutor} {
set wa [expr {[string length $a]+1}]
set wb [expr {$wa+[string length $b]-1}]
puts stderr "Ethiopian multiplication of $a and $b"
interp alias {} logmult {} apply {{wa wb msg} {
upvar 1 a a b b
puts stderr [format "%*d %*d %s" $wa $a $wb $b $msg]
return 0
}} $wa $wb
} else {
proc logmult args {return 0}
}
return [expr {mult($a,$b)}]
} |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Scheme | Scheme | ; uses SRFI-1 library http://srfi.schemers.org/srfi-1/srfi-1.html
(define (evolve ls r)
(unfold
(lambda (x) (null? (cddr x)))
(lambda (x)
(vector-ref r (+ (* 4 (first x)) (* 2 (second x)) (third x))))
cdr
(cons (last ls) (append ls (list (car ls))))))
(define (automaton s r n)
(define (*automaton s0 rv n)
(for-each (lambda (x) (display (if (zero? x) #\. #\#))) s0)
(newline)
(if (not (zero? n))
(let ((s1 (evolve s0 rv)))
(*automaton s1 rv (- n 1)))))
(display "Rule ")
(display r)
(newline)
(*automaton
s
(list->vector
(append
(int->bin r)
(make-list (- 7 (floor (/ (log r) (log 2)))) 0)))
n))
(automaton '(0 1 0 0 0 1 0 1 0 0 1 1 1 1 0 0 0 0 0 1) 30 20) |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #WDTE | WDTE | let max a b => a { < b => b };
let ! n => n { > 1 => - n 1 -> ! -> * n } -> max 1; |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #Python | Python | import SocketServer
HOST = "localhost"
PORT = 12321
# this server uses ThreadingMixIn - one thread per connection
# replace with ForkMixIn to spawn a new process per connection
class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
# no need to override anything - default behavior is just fine
pass
class EchoRequestHandler(SocketServer.StreamRequestHandler):
"""
Handles one connection to the client.
"""
def handle(self):
print "connection from %s" % self.client_address[0]
while True:
line = self.rfile.readline()
if not line: break
print "%s wrote: %s" % (self.client_address[0], line.rstrip())
self.wfile.write(line)
print "%s disconnected" % self.client_address[0]
# Create the server
server = EchoServer((HOST, PORT), EchoRequestHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
print "server listening on %s:%s" % server.server_address
server.serve_forever() |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #PicoLisp | PicoLisp | (de _eban? (N)
(let
(B (/ N 1000000000)
R (% N 1000000000)
M (/ R 1000000)
R (% N 1000000)
Z (/ R 1000)
R (% R 1000) )
(and
(>= M 30)
(<= M 66)
(setq M (% M 10)) )
(and
(>= Z 30)
(<= Z 66)
(setq Z (% Z 10)) )
(and
(>= R 30)
(<= R 66)
(setq R (% R 10)) )
(fully
'((S)
(unless (bit? 1 (val S))
(>= 6 (val S)) ) )
'(B M Z R) ) ) )
(de eban (B A)
(default A 2)
(let R (cons 0 (cons))
(for (N A (>= B N) (+ N 2))
(and
(_eban? N)
(inc R)
(push (cdr R) N) ) )
(con R (flip (cadr R)))
R ) )
(off R)
(prinl "eban numbers up to an including 1000:")
(setq R (eban 1000))
(println (cdr R))
(prinl "count: " (car R))
(prinl)
(prinl "eban numbers between 1000 and 4000")
(setq R (eban 4000 1000))
(println (cdr R))
(prinl "count: " (car R))
(prinl)
(prinl "eban numbers up to an including 10000:")
(prinl "count: " (car (eban 10000)))
(prinl)
(prinl "eban numbers up to an including 100000:")
(prinl "count: " (car (eban 100000)))
(prinl)
(prinl "eban numbers up to an including 1000000:")
(prinl "count: " (car (eban 1000000)))
(prinl)
(prinl "eban numbers up to an including 10000000:")
(prinl "count: " (car (eban 10000000))) |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #Python | Python |
# Use inflect
"""
show all eban numbers <= 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
"""
import inflect
import time
before = time.perf_counter()
p = inflect.engine()
# eban numbers <= 1000
print(' ')
print('eban numbers up to and including 1000:')
print(' ')
count = 0
for i in range(1,1001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print('count = '+str(count))
print(' ')
# eban numbers 1000 to 4000
print(' ')
print('eban numbers between 1000 and 4000 (inclusive):')
print(' ')
count = 0
for i in range(1000,4001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print('count = '+str(count))
print(' ')
# eban numbers up to 10000
print(' ')
print('eban numbers up to and including 10000:')
print(' ')
count = 0
for i in range(1,10001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
# eban numbers up to 100000
print(' ')
print('eban numbers up to and including 100000:')
print(' ')
count = 0
for i in range(1,100001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
# eban numbers up to 1000000
print(' ')
print('eban numbers up to and including 1000000:')
print(' ')
count = 0
for i in range(1,1000001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
# eban numbers up to 10000000
print(' ')
print('eban numbers up to and including 10000000:')
print(' ')
count = 0
for i in range(1,10000001):
if not 'e' in p.number_to_words(i):
count += 1
print(' ')
print('count = '+str(count))
print(' ')
after = time.perf_counter()
print(" ")
print("Run time in seconds: "+str(after - before))
|
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related tasks
Draw a cuboid
write language name in 3D ASCII
| #J | J | require'gl2 gles ide/qt/opengl'
coinsert'jgl2 jgles qtopengl'
rotcube=: {{
if.0=nc<'sprog'do.return.end.
fixosx=. 'opengl';'opengl',('DARWIN'-:UNAME)#' version 4.1'
wd 'pc rot; minwh 300 300; cc cube opengl flush' rplc fixosx
HD=: ".wd 'qhwndc cube'
wd 'ptimer 17; pshow'
}}
rot_close=: {{
wd 'ptimer 0'
glDeleteBuffers ::0: 2; vbo
glDeleteProgram ::0: sprog
erase 'sprog'
wd 'pclose'
}}
cstr=: {{if.y do.memr y,0 _1 2 else.EMPTY end.}}
gstr=: {{cstr>{.glGetString y}}
diag=: {{p[echo y,': ',p=.gstr".y}}
blitf=: {{
dat=. 1 fc,y NB. short floats
glBindBuffer GL_ARRAY_BUFFER; x{vbo
glBufferData GL_ARRAY_BUFFER; (#dat); (symdat<'dat'); GL_STATIC_DRAW
}}
rot_cube_initialize=: {{
erase'sprog'
if.0=#diag 'GL_VERSION' do.echo 'cannot retrieve GL_VERSION' return.end.
diag each;:'GL_VENDOR GL_RENDERER GL_SHADING_LANGUAGE_VERSION'
GLSL=:wglGLSL''
wglPROC''
'err program'=. gl_makeprogram VSRC ;&fixversion FSRC
if.#err do. echo 'err: ', err return.end.
if. GLSL>120 do.vao=: >{:glGenVertexArrays 1;,_1 end.
assert _1~:vertexAttr=: >{.glGetAttribLocation program;'vertex'
assert _1~:colorAttr=: >{.glGetAttribLocation program;'color'
assert _1~:mvpUni=: >{.glGetUniformLocation program;'mvp'
vbo=: >{:glGenBuffers 2;2#_1
0 blitf vertexData
1 blitf colorData
sprog=: program
}}
VSRC=: {{)n
#version $version
$v_in $highp vec3 vertex;
$v_in $lowp vec3 color;
$v_out $lowp vec4 v_color;
uniform mat4 mvp;
void main(void) {
gl_Position= mvp * vec4(vertex,1.0);
v_color= vec4(color,1.0);
}
}}
FSRC=: {{)n
#version $version
$f_in $lowp vec4 v_color;
$fragColor
void main(void) {
$gl_fragColor= v_color;
}
}}
fixversion=: {{
NB. cope with host shader language version
r=. '$version';GLSL,&":;(GLSL>:300)#(*GLES_VERSION){' core';' es'
f1=. GLSL<:120
r=.r, '$v_in';f1{'in';'attribute'
r=.r, '$v_out';f1{'out';'varying'
r=.r, '$f_in';f1{'in';'varying'
r=.r, '$highp ';f1#(*GLES_VERSION)#'highp'
r=.r, '$lowp ';f1#(*GLES_VERSION)#'lowp'
f2=.(330<:GLSL)+.(300<:GLSL)**GLES_VERSION
r=.r, '$gl_fragColor';f2{'gl_FragColor';'fragColor'
r=.r, '$fragColor';f2#'out vec4 fragColor;'
y rplc r
}}
rot_timer=: {{
try.
gl_sel HD
gl_paint''
catch.
echo 'error in rot_timer',LF,13!:12''
wd'ptimer 0'
end.
}}
zeroVAttr=: {{
glEnableVertexAttribArray y
glBindBuffer GL_ARRAY_BUFFER; x{vbo
glVertexAttribPointer y; 3; GL_FLOAT; 0; 0; 0
}}
mp=: +/ .*
ref=: (gl_Translate 0 0 _10) mp glu_LookAt 0 0 1,0 0 0,1 0 0
rot_cube_paint=: {{
try.
if.nc<'sprog' do.return.end.
wh=. gl_qwh''
glClear GL_COLOR_BUFFER_BIT+GL_DEPTH_BUFFER_BIT [glClearColor 0 0 0 0+%3
glUseProgram sprog
glEnable each GL_DEPTH_TEST, GL_CULL_FACE, GL_BLEND
glBlendFunc GL_SRC_ALPHA; GL_ONE_MINUS_SRC_ALPHA
mvp=. (gl_Rotate (360|60*6!:1''),1 0 0)mp ref mp gl_Perspective 30, (%/wh),1 20
glUniformMatrix4fv mvpUni; 1; GL_FALSE; mvp
if. GLSL>120 do. glBindVertexArray {.vao end.
0 zeroVAttr vertexAttr
1 zeroVAttr colorAttr
glDrawArrays GL_TRIANGLES; 0; 36
glUseProgram 0
catch.
echo 'error in rot_cube_paint',LF,13!:12''
wd'ptimer 0'
end.
}}
NB. oriented triangle representation of unit cube
unitCube=: #:(0 1 2, 2 1 3)&{@".;._2 {{)n
2 3 0 1 NB. unit cube corner indices
3 7 1 5 NB. 0: origin
4 0 5 1 NB. 1, 2, 4: unit distance along each axis
6 2 4 0 NB. 3, 5, 6, 7: combinations of axes
7 6 5 4
7 3 6 2
}}
NB. orient cube so diagonal is along first axis
daxis=: (_1^5 6 e.~i.3 3)*%:6%~2 0 4,2 3 1,:2 3 1
vertexData=:(_1^unitCube)mp daxis NB. cube with center at origin
colorData=: unitCube NB. corresponding colors
rotcube'' |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #PARI.2FGP | PARI/GP | multMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]*B[i,j]);
divMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]/B[i,j]);
powMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]^B[i,j]); |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #AutoHotkey | AutoHotkey | #NoEnv
SetBatchLines, -1
#SingleInstance, Force
; Uncomment if Gdip.ahk is not in your standard library
#Include, Gdip.ahk
; Settings
X := 200, Y := 200, Width := 200, Height := 200 ; Location and size of sphere
rotation := -30 ; degrees
ARGB := 0xFFFF0000 ; Color=Solid Red
If !pToken := Gdip_Startup() ; Start gdi+
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, Exit
Gui, -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs ; Create GUI
Gui, Show, NA ; Show GUI
hwnd1 := WinExist() ; Get a handle to this window we have created in order to update it later
hbm := CreateDIBSection(A_ScreenWidth, A_ScreenHeight) ; Create a gdi bitmap drawing area
hdc := CreateCompatibleDC() ; Get a device context compatible with the screen
obm := SelectObject(hdc, hbm) ; Select the bitmap into the device context
pGraphics := Gdip_GraphicsFromHDC(hdc) ; Get a pointer to the graphics of the bitmap, for use with drawing functions
Gdip_SetSmoothingMode(pGraphics, 4) ; Set the smoothing mode to antialias = 4 to make shapes appear smother
Gdip_TranslateWorldTransform(pGraphics, X, Y)
Gdip_RotateWorldTransform(pGraphics, rotation)
; Base ellipse
pBrush := Gdip_CreateLineBrushFromRect(0, 0, Width, Height, ARGB, 0xFF000000)
Gdip_FillEllipse(pGraphics, pBrush, 0, 0, Width, Height)
; First highlight ellipse
pBrush := Gdip_CreateLineBrushFromRect(Width*0.1, Height*0.01, Width*0.8, Height*0.6, 0x33FFFFFF, 0x00FFFFFF)
Gdip_FillEllipse(pGraphics, pBrush, Width*0.1, Height*0.01, Width*0.8, Height*0.6)
; Second highlight ellipse
pBrush := Gdip_CreateLineBrushFromRect(Width*0.3, Height*0.02, Width*0.3, Height*0.2, 0xBBFFFFFF, 0x00FFFFFF)
Gdip_FillEllipse(pGraphics, pBrush, Width*0.3, Height*0.02, Width*0.3, Height*0.2)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, A_ScreenWidth, A_ScreenHeight)
SelectObject(hdc, obm) ; Select the object back into the hdc
Gdip_DeletePath(Path)
Gdip_DeleteBrush(pBrush)
DeleteObject(hbm) ; Now the bitmap may be deleted
DeleteDC(hdc) ; Also the device context related to the bitmap may be deleted
Gdip_DeleteGraphics(G) ; The graphics may now be deleted
Return
Exit:
; gdi+ may now be shutdown on exiting the program
Gdip_Shutdown(pToken)
ExitApp |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Delphi | Delphi |
program Element_insertion;
{$APPTYPE CONSOLE}
uses
System.SysUtils,Boost.LinkedList;
var
List:TLinkedList<Integer>;
Node:TLinkedListNode<Integer>;
begin
List := TLinkedList<Integer>.Create;
Node:= List.Add(5);
List.AddAfter(Node,7);
List.AddAfter(Node,15);
Writeln(List.ToString);
List.Free;
Readln;
end. |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #E | E | def insert(after, value) {
def newNode := makeElement(value, after, after.getNext())
after.getNext().setPrev(newNode)
after.setNext(newNode)
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Erlang | Erlang | 2> doubly_linked_list:task().
foreach_next a
foreach_next c
foreach_next b
foreach_previous b
foreach_previous c
foreach_previous a
|
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace RosettaCode.DoublyLinkedList
{
internal static class Program
{
private static void Main()
{
var list = new LinkedList<char>("hello");
var current = list.First;
do
{
Console.WriteLine(current.Value);
} while ((current = current.Next) != null);
Console.WriteLine();
current = list.Last;
do
{
Console.WriteLine(current.Value);
} while ((current = current.Previous) != null);
}
}
} |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C.2B.2B | C++ | #include <iostream>
#include <list>
int main ()
{
std::list<int> numbers {1, 5, 7, 0, 3, 2};
for(const auto& i: numbers)
std::cout << i << ' ';
std::cout << '\n';
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* structure Node Doublylinked List*/
.struct 0
NDlist_next: @ next element
.struct NDlist_next + 4
NDlist_prev: @ previous element
.struct NDlist_prev + 4
NDlist_value: @ element value or key
.struct NDlist_value + 4
NDlist_fin:
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #AutoHotkey | AutoHotkey | Lbl LINK
r₂→{r₁}ʳ
0→{r₁+2}ʳ
0→{r₁+4}ʳ
r₁
Return
Lbl NEXT
{r₁+2}ʳ
Return
Lbl PREV
{r₁+4}ʳ
Return
Lbl VALUE
{r₁}ʳ
Return |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Axe | Axe | Lbl LINK
r₂→{r₁}ʳ
0→{r₁+2}ʳ
0→{r₁+4}ʳ
r₁
Return
Lbl NEXT
{r₁+2}ʳ
Return
Lbl PREV
{r₁+4}ʳ
Return
Lbl VALUE
{r₁}ʳ
Return |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
Task
Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
Sort the balls in a way idiomatic to your language.
Check the sorted balls are in the order of the Dutch national flag.
C.f.
Dutch national flag problem
Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
// Dutch national flag problem
template <typename BidIt, typename T>
void dnf_partition(BidIt first, BidIt last, const T& low, const T& high)
{
for (BidIt next = first; next != last; ) {
if (*next < low) {
std::iter_swap(first++, next++);
} else if (!(*next < high)) {
std::iter_swap(next, --last);
} else {
++next;
}
}
}
enum Colors { RED, WHITE, BLUE };
void print(const Colors *balls, size_t size)
{
static const char *label[] = { "red", "white", "blue" };
std::cout << "Balls:";
for (size_t i = 0; i < size; ++i) {
std::cout << ' ' << label[balls[i]];
}
std::cout << "\nSorted: " << std::boolalpha << std::is_sorted(balls, balls + size) << '\n';
}
int main()
{
Colors balls[] = { RED, WHITE, BLUE, RED, WHITE, BLUE, RED, WHITE, BLUE };
std::random_shuffle(balls, balls + 9);
print(balls, 9);
dnf_partition(balls, balls + 9, WHITE, BLUE);
print(balls, 9);
} |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Befunge | Befunge | " :htdiW">:#,_>&>00p" :thgieH">:#,_>&>:10p0" :htpeD">:#,_$>&>:20p55+,+:1`*:vv
v\-*`0:-g01\++*`\0:-\-1g01:\-*`0:-g02\+*`\0:-\-1g02<:::::<\g3`\g01:\1\+55\1-1_v
>":"\1\:20g\`!3g:30p\00g2*\::20g\`\20g1-\`+1+3g\1\30g\:20g-::0\`\2*1+*-\48*\:^v
/\_ @_\#!:!#$>#$_\#!:,#-\#1 <+1\<*84g02"_"+1*2g00+551$< |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Oforth | Oforth | : createVar(varname)
"tvar: " varname + eval ;
"myvar" createVar
12 myvar put
myvar at . |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #PARI.2FGP | PARI/GP | eval(Str(input(), "=34")) |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Pascal | Pascal |
PROGRAM ExDynVar;
{$IFDEF FPC}
{$mode objfpc}{$H+}{$J-}{R+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
(*)
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
The free and readable alternative at C/C++ speeds
compiles natively to almost any platform, including raspberry PI
This demo uses a dictionary because it is compiled: it cannot make
dynamic variables at runtime.
(*)
USES
Generics.Collections,
SysUtils,
Variants;
TYPE
Tdict =
{$IFDEF FPC}
specialize
{$ENDIF}
TDictionary < ansistring, variant > ;
VAR
VarName: ansistring;
strValue: ansistring;
VarValue: variant;
D: Tdict;
FUNCTION SetType ( strVal: ansistring ) : variant ;
(*)
If the value is numeric, store it as numeric, otherwise store it as ansistring
(*)
BEGIN
TRY
SetType := StrToFloat ( strVal ) ;
EXCEPT
SetType := strVal ;
END;
END;
BEGIN
D := TDict.Create;
REPEAT
Write ( 'Enter variable name : ' ) ;
ReadLn ( VarName ) ;
Write ( 'Enter variable Value : ' ) ;
ReadLn ( strValue ) ;
VarValue := SetType ( strValue ) ;
TRY
BEGIN
D.AddOrSetValue ( VarName, VarValue ) ;
Write ( VarName ) ;
Write ( ' = ' ) ;
WriteLn ( D [ VarName ] ) ;
END;
EXCEPT
WriteLn ( 'Something went wrong.. Try again' ) ;
END;
UNTIL ( strValue = '' ) ;
D.Free;
END.
|
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Lua | Lua | local SDL = require "SDL"
local ret = SDL.init { SDL.flags.Video }
local window = SDL.createWindow {
title = "Pixel",
height = 320,
width = 240
}
local renderer = SDL.createRenderer(window, 0, 0)
renderer:clear()
renderer:setDrawColor(0xFF0000)
renderer:drawPoint({x = 100,y = 100})
renderer:present()
SDL.delay(5000)
|
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | CreateWindow[PaletteNotebook[{Graphics[{Red, Point[{100, 100}]}]}], WindowSize -> {320, 240}] |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Python | Python | from itertools import product
def egyptian_divmod(dividend, divisor):
assert divisor != 0
pwrs, dbls = [1], [divisor]
while dbls[-1] <= dividend:
pwrs.append(pwrs[-1] * 2)
dbls.append(pwrs[-1] * divisor)
ans, accum = 0, 0
for pwr, dbl in zip(pwrs[-2::-1], dbls[-2::-1]):
if accum + dbl <= dividend:
accum += dbl
ans += pwr
return ans, abs(accum - dividend)
if __name__ == "__main__":
# Test it gives the same results as the divmod built-in
for i, j in product(range(13), range(1, 13)):
assert egyptian_divmod(i, j) == divmod(i, j)
# Mandated result
i, j = 580, 34
print(f'{i} divided by {j} using the Egyption method is %i remainder %i'
% egyptian_divmod(i, j)) |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #Python | Python | from fractions import Fraction
from math import ceil
class Fr(Fraction):
def __repr__(self):
return '%s/%s' % (self.numerator, self.denominator)
def ef(fr):
ans = []
if fr >= 1:
if fr.denominator == 1:
return [[int(fr)], Fr(0, 1)]
intfr = int(fr)
ans, fr = [[intfr]], fr - intfr
x, y = fr.numerator, fr.denominator
while x != 1:
ans.append(Fr(1, ceil(1/fr)))
fr = Fr(-y % x, y* ceil(1/fr))
x, y = fr.numerator, fr.denominator
ans.append(fr)
return ans
if __name__ == '__main__':
for fr in [Fr(43, 48), Fr(5, 121), Fr(2014, 59)]:
print('%r ─► %s' % (fr, ' '.join(str(x) for x in ef(fr))))
lenmax = denommax = (0, None)
for fr in set(Fr(a, b) for a in range(1,100) for b in range(1, 100)):
e = ef(fr)
#assert sum((f[0] if type(f) is list else f) for f in e) == fr, 'Whoops!'
elen, edenom = len(e), e[-1].denominator
if elen > lenmax[0]:
lenmax = (elen, fr, e)
if edenom > denommax[0]:
denommax = (edenom, fr, e)
print('Term max is %r with %i terms' % (lenmax[1], lenmax[0]))
dstr = str(denommax[0])
print('Denominator max is %r with %i digits %s...%s' %
(denommax[1], len(dstr), dstr[:5], dstr[-5:])) |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
ASK "insert number1", nr1=""
ASK "insert number2", nr2=""
SET nrs=APPEND(nr1,nr2),size_nrs=SIZE(nrs)
IF (size_nrs!=2) ERROR/STOP "insert two numbers"
LOOP n=nrs
IF (n!='digits') ERROR/STOP n, " is not a digit"
ENDLOOP
PRINT "ethopian multiplication of ",nr1," and ",nr2
SET sum=0
SECTION checkifeven
SET even=MOD(nr1,2)
IF (even==0) THEN
SET action="struck"
ELSE
SET action="kept"
SET sum=APPEND (sum,nr2)
ENDIF
SET nr1=CENTER (nr1,+6),nr2=CENTER (nr2,+6),action=CENTER (action,8)
PRINT nr1,nr2,action
ENDSECTION
SECTION halve_i
SET nr1=nr1/2
ENDSECTION
SECTION double_i
nr2=nr2*2
ENDSECTION
DO checkifeven
LOOP
DO halve_i
DO double_i
DO checkifeven
IF (nr1==1) EXIT
ENDLOOP
SET line=REPEAT ("=",20), sum = sum(sum),sum=CENTER (sum,+12)
PRINT line
PRINT sum
|
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Sidef | Sidef | class Automaton(rule, cells) {
method init {
rule = sprintf("%08b", rule).chars.map{.to_i}.reverse
}
method next {
var previous = cells.map{_}
var len = previous.len
cells[] = rule[
previous.range.map { |i|
4*previous[i-1 % len] +
2*previous[i] +
previous[i+1 % len]
}
]
}
method to_s {
cells.map { _ ? '#' : ' ' }.join
}
}
var size = 20
var arr = size.of(0)
arr[size/2] = 1
var auto = Automaton(90, arr)
(size/2).times {
print "|#{auto}|\n"
auto.next
} |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #WebAssembly | WebAssembly |
(module
;; recursive
(func $fac (param f64) (result f64)
get_local 0
f64.const 1
f64.lt
if (result f64)
f64.const 1
else
get_local 0
get_local 0
f64.const 1
f64.sub
call $fac
f64.mul
end)
(export "fac" (func $fac)))
|
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #Racket | Racket |
#lang racket
(define listener (tcp-listen 12321))
(let echo-server ()
(define-values [I O] (tcp-accept listener))
(thread (λ() (copy-port I O) (close-output-port O)))
(echo-server))
|
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #Raku | Raku | use Lingua::EN::Numbers;
sub nban ($seq, $n = 'e') { ($seq).map: { next if .&cardinal.contains(any($n.lc.comb)); $_ } }
sub enumerate ($n, $upto) {
my @ban = [nban(1 .. 99, $n)],;
my @orders;
(2 .. $upto).map: -> $o {
given $o % 3 { # Compensate for irregulars: 11 - 19
when 1 { @orders.push: [flat (10**($o - 1) X* 10 .. 19).map(*.&nban($n)), |(10**$o X* 2 .. 9).map: *.&nban($n)] }
default { @orders.push: [flat (10**$o X* 1 .. 9).map: *.&nban($n)] }
}
}
^@orders .map: -> $o {
@ban.push: [] and next unless +@orders[$o];
my @these;
@orders[$o].map: -> $m {
@these.push: $m;
for ^@ban -> $b {
next unless +@ban[$b];
@these.push: $_ for (flat @ban[$b]) »+» $m ;
}
}
@ban.push: @these;
}
@ban.unshift(0) if nban(0, $n);
flat @ban.map: *.flat;
}
sub count ($n, $upto) {
my @orders;
(2 .. $upto).map: -> $o {
given $o % 3 { # Compensate for irregulars: 11 - 19
when 1 { @orders.push: [flat (10**($o - 1) X* 10 .. 19).map(*.&nban($n)), |(10**$o X* 2 .. 9).map: *.&nban($n)] }
default { @orders.push: [flat (10**$o X* 1 .. 9).map: *.&nban($n)] }
}
}
my @count = +nban(1 .. 99, $n);
^@orders .map: -> $o {
@count.push: 0 and next unless +@orders[$o];
my $prev = so (@orders[$o].first( { $_ ~~ /^ '1' '0'+ $/ } ) // 0 );
my $sum = @count.sum;
my $these = +@orders[$o] * $sum + @orders[$o];
$these-- if $prev;
@count[1 + $o] += $these;
++@count[$o] if $prev;
}
++@count[0] if nban(0, $n);
[\+] @count;
}
#for < e o t tali subur tur ur cali i u > -> $n { # All of them
for < e t subur > -> $n { # An assortment for demonstration
my $upto = 21; # 1e21
my @bans = enumerate($n, 4);
my @counts = count($n, $upto);
# DISPLAY
my @k = @bans.grep: * < 1000;
my @j = @bans.grep: 1000 <= * <= 4000;
put "\n============= {$n}-ban: =============\n" ~
"{$n}-ban numbers up to 1000: {+@k}\n[{@k».&comma}]\n\n" ~
"{$n}-ban numbers between 1,000 & 4,000: {+@j}\n[{@j».&comma}]\n" ~
"\nCounts of {$n}-ban numbers up to {cardinal 10**$upto}"
;
my $s = max (1..$upto).map: { (10**$_).&cardinal.chars };
@counts.unshift: @bans.first: * > 10, :k;
for ^$upto -> $c {
printf "Up to and including %{$s}s: %s\n", cardinal(10**($c+1)), comma(@counts[$c]);
}
} |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related tasks
Draw a cuboid
write language name in 3D ASCII
| #Java | Java | import java.awt.*;
import java.awt.event.ActionEvent;
import static java.lang.Math.*;
import javax.swing.*;
public class RotatingCube extends JPanel {
double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},
{1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};
int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};
public RotatingCube() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
scale(100);
rotateCube(PI / 4, atan(sqrt(2)));
new Timer(17, (ActionEvent e) -> {
rotateCube(PI / 180, 0);
repaint();
}).start();
}
final void scale(double s) {
for (double[] node : nodes) {
node[0] *= s;
node[1] *= s;
node[2] *= s;
}
}
final void rotateCube(double angleX, double angleY) {
double sinX = sin(angleX);
double cosX = cos(angleX);
double sinY = sin(angleY);
double cosY = cos(angleY);
for (double[] node : nodes) {
double x = node[0];
double y = node[1];
double z = node[2];
node[0] = x * cosX - z * sinX;
node[2] = z * cosX + x * sinX;
z = node[2];
node[1] = y * cosY - z * sinY;
node[2] = z * cosY + y * sinY;
}
}
void drawCube(Graphics2D g) {
g.translate(getWidth() / 2, getHeight() / 2);
for (int[] edge : edges) {
double[] xy1 = nodes[edge[0]];
double[] xy2 = nodes[edge[1]];
g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),
(int) round(xy2[0]), (int) round(xy2[1]));
}
for (double[] node : nodes)
g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawCube(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Rotating Cube");
f.setResizable(false);
f.add(new RotatingCube(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #Perl | Perl | package Elementwise;
use Exporter 'import';
use overload
'=' => sub { $_[0]->clone() },
'+' => sub { $_[0]->add($_[1]) },
'-' => sub { $_[0]->sub($_[1]) },
'*' => sub { $_[0]->mul($_[1]) },
'/' => sub { $_[0]->div($_[1]) },
'**' => sub { $_[0]->exp($_[1]) },
;
sub new
{
my ($class, $v) = @_;
return bless $v, $class;
}
sub clone
{
my @ret = @{$_[0]};
return bless \@ret, ref($_[0]);
}
sub add { new Elementwise ref($_[1]) ? [map { $_[0][$_] + $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] + $_[1] } 0 .. $#{$_[0]} ] }
sub sub { new Elementwise ref($_[1]) ? [map { $_[0][$_] - $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] - $_[1] } 0 .. $#{$_[0]} ] }
sub mul { new Elementwise ref($_[1]) ? [map { $_[0][$_] * $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] * $_[1] } 0 .. $#{$_[0]} ] }
sub div { new Elementwise ref($_[1]) ? [map { $_[0][$_] / $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] / $_[1] } 0 .. $#{$_[0]} ] }
sub exp { new Elementwise ref($_[1]) ? [map { $_[0][$_] ** $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] ** $_[1] } 0 .. $#{$_[0]} ] }
1; |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #AWK | AWK |
# syntax: GAWK -f DRAW_A_SPHERE.AWK
# converted from VBSCRIPT
BEGIN {
draw_sphere(20,4,0.1)
draw_sphere(10,2,0.4)
exit(0)
}
function draw_sphere(radius,k,ambient, b,i,intensity,j,leng_shades,light,line,shades,vec,x,y) {
leng_shades = split0(".:!*oe&#%@",shades,"")
split("30,30,-50",light,",")
normalize(light)
for (i=int(-radius); i<=ceil(radius); i++) {
x = i + 0.5
line = ""
for (j=int(-2*radius); j<=ceil(2*radius); j++) {
y = j / 2 + 0.5
if (x*x + y*y <= radius*radius) {
vec[1] = x
vec[2] = y
vec[3] = sqrt(radius*radius - x*x - y*y)
normalize(vec)
b = dot(light,vec) ^ k + ambient
intensity = int((1-b) * leng_shades)
if (intensity < 0) {
intensity = 0
}
if (intensity >= leng_shades) {
intensity = leng_shades
}
line = line shades[intensity]
}
else {
line = line " "
}
}
printf("%s\n",line)
}
}
function ceil(x, tmp) {
tmp = int(x)
return (tmp != x) ? tmp+1 : tmp
}
function dot(x,y, tmp) {
tmp = x[1]*y[1] + x[2]*y[2] + x[3]*y[3]
return (tmp < 0) ? -tmp : 0
}
function normalize(v, tmp) {
tmp = sqrt(v[1]*v[1] + v[2]*v[2] + v[3]*v[3])
v[1] /= tmp
v[2] /= tmp
v[3] /= tmp
}
function split0(str,array,fs, arr,i,n) { # same as split except indices start at zero
n = split(str,arr,fs)
for (i=1; i<=n; i++) {
array[i-1] = arr[i]
}
return(n)
}
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Fortran | Fortran | module dlList
public :: node, insertAfter, getNext
type node
real :: data
type( node ), pointer :: next => null()
type( node ), pointer :: previous => null()
end type node
contains
subroutine insertAfter(nodeBefore, value)
type( node ), intent(inout), target :: nodeBefore
type( node ), pointer :: newNode
real, intent(in) :: value
allocate( newNode )
newNode%data = value
newNode%next => nodeBefore%next
newNode%previous => nodeBefore
if (associated( newNode%next )) then
newNode%next%previous => newNode
end if
newNode%previous%next => newNode
end subroutine insertAfter
subroutine delete(current)
type( node ), intent(inout), pointer :: current
if (associated( current%next )) current%next%previous => current%previous
if (associated( current%previous )) current%previous%next => current%next
deallocate(current)
end subroutine delete
end module dlList
program dlListTest
use dlList
type( node ), target :: head
type( node ), pointer :: current, next
head%data = 1.0
current => head
do i = 1, 20
call insertAfter(current, 2.0**i)
current => current%next
end do
current => head
do while (associated(current))
print *, current%data
next => current%next
if (.not. associated(current, head)) call delete(current)
current => next
end do
end program dlListTest |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Clojure | Clojure | (def dl (double-list [:a :b :c :d]))
;=> #'user/dl
((juxt seq rseq) dl)
;=> [(:a :b :c :d) (:d :c :b :a)]
(take-while identity (iterate get-next (get-head dl)))
;=> (#:double_list.Node{:prev nil, :next #<Object...>, :data :a, :key #<Object...>}
;=> #:double_list.Node{:prev #<Object...>, :next #<Object...>, :data :b, :key #<Object...>}
;=> #:double_list.Node{:prev #<Object...>, :next #<Object...>, :data :c, :key #<Object...>}
;=> #:double_list.Node{:prev #<Object...>, :next nil, :data :d, :key #<Object...>})
(take-while identity (iterate get-prev (get-tail dl)))
;=> (#:double_list.Node{:prev #<Object...>, :next nil, :data :d, :key #<Object...>}
;=> #:double_list.Node{:prev #<Object...>, :next #<Object...>, :data :c, :key #<Object...>}
;=> #:double_list.Node{:prev #<Object...>, :next #<Object...>, :data :b, :key #<Object...>}
;=> #:double_list.Node{:prev nil, :next #<Object...>, :data :a, :key #<Object...>}) |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #D | D | void main() {
import std.stdio, std.container, std.range;
auto dll = DList!dchar("DCBA"d.dup);
dll[].writeln;
dll[].retro.writeln;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #BBC_BASIC | BBC BASIC | DIM node{pPrev%, pNext%, iData%}
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Bracmat | Bracmat | link=(prev=) (next=) (data=) |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C | C | struct Node
{
struct Node *next;
struct Node *prev;
void *data;
}; |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
Task
Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
Sort the balls in a way idiomatic to your language.
Check the sorted balls are in the order of the Dutch national flag.
C.f.
Dutch national flag problem
Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| #C_sharp | C_sharp | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCode
{
class Program
{
static void QuickSort(IComparable[] elements, int left, int right)
{
int i = left, j = right;
IComparable pivot = elements[left + (right - left) / 2];
while (i <= j)
{
while (elements[i].CompareTo(pivot) < 0) i++;
while (elements[j].CompareTo(pivot) > 0) j--;
if (i <= j)
{
// Swap
IComparable tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
i++;
j--;
}
}
// Recursive calls
if (left < j) QuickSort(elements, left, j);
if (i < right) QuickSort(elements, i, right);
}
const int NUMBALLS = 5;
static void Main(string[] args)
{
Func<string[], bool> IsSorted = (ballList) =>
{
int state = 0;
for (int i = 0; i < NUMBALLS; i++)
{
if (int.Parse(ballList[i]) < state)
return false;
if (int.Parse(ballList[i]) > state)
state = int.Parse(ballList[i]);
}
return true;
};
Func<string[], string> PrintOut = (ballList2) =>
{
StringBuilder str = new StringBuilder();
for (int i = 0; i < NUMBALLS; i++)
str.Append(int.Parse(ballList2[i]) == 0 ? "r" : int.Parse(ballList2[i]) == 1 ? "w" : "b");
return str.ToString();
};
bool continueLoop = true;
string[] balls = new string[NUMBALLS]; // 0 = r, 1 = w, 2 = b
Random numberGenerator = new Random();
do // Enforce that we start with non-sorted balls
{
// Generate balls
for (int i = 0; i < NUMBALLS; i++)
balls[i] = numberGenerator.Next(3).ToString();
continueLoop = IsSorted(balls);
if (continueLoop)
Console.WriteLine("Accidentally still sorted: {0}", PrintOut(balls));
} while (continueLoop);
Console.WriteLine("Non-sorted: {0}", PrintOut(balls));
QuickSort(balls, 0, NUMBALLS - 1); // Sort them using quicksort
Console.WriteLine("{0}: {1}", IsSorted(balls) ? "Sorted" : "Sort failed", PrintOut(balls));
}
}
}
|
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Brlcad | Brlcad | opendb cuboid.g y # Create a database to hold our shapes
units cm # Set the unit of measure
in cuboid.s rpp 0 2 0 3 0 4 # Create a 2 x 3 x 4 cuboid named cuboid.s |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Perl | Perl | print "Enter a variable name: ";
$varname = <STDIN>; # type in "foo" on standard input
chomp($varname);
$$varname = 42; # when you try to dereference a string, it will be
# treated as a "symbolic reference", where they
# take the string as the name of the variable
print "$foo\n"; # prints "42" |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Phix | Phix | constant globals = new_dict()
while 1 do
string name = prompt_string("Enter name or press Enter to quit:")
if length(name)=0 then exit end if
bool bExists = (getd_index(name,globals)!=NULL)
string prompt = iff(not bExists?"No such name, enter a value:"
:sprintf("Already exists, new value[%s]:",{getd(name,globals)}))
string data = prompt_string(prompt)
if length(data) then
setd(name,data,globals)
end if
end while |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #PHP | PHP | <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?> |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Module PlotPixel (a as single, b as single) {
Move a*TwipsX, b*TwipsX
Draw TwipsX, TwipsY
}
Cls 5,0 \\ clear console with Magenta (5) and set split screen from 0 (no split screen)
Pen #55FF77 {
PlotPixel 1000, 200
}
Wait 1000
Title "", 1
Declare DrawPixelForm Form
With DrawPixelForm, "Title", "Draw a Pixel at 100,100"
Layer DrawPixelForm {
\\ 12 for 12pt fonts
\\ use ; to center window
Window 12, 320*twipsx, 240*twipsy;
Cls #333333
Pen Color(255,0,0) {
PlotPixel 100, 100
}
}
\\ code to show/hide console clicking form
\\ console shown behind form
k=0
Function DrawPixelForm.Click {
Title "Rosetta Code Example", abs(k)
if k then show
k~
}
Method DrawPixelForm, "Show", 1
Declare DrawPixelForm Nothing
}
CheckIt
|
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Nim | Nim | import rapid/gfx
var
window = initRWindow()
.size(320, 240)
.title("Rosetta Code - draw a pixel")
.open()
surface = window.openGfx()
surface.loop:
draw ctx, step:
ctx.clear(gray(0))
ctx.begin()
ctx.point((100.0, 100.0, rgb(255, 0, 0)))
ctx.draw(prPoints)
discard step # Prevent unused variable warnings
update step:
discard step |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Quackery | Quackery | [ dup 0 = if
[ $ "Cannot divide by zero."
fail ]
[] unrot
[ 2dup < not while
rot over swap join
unrot dup + again ]
drop swap
dup size
[] 1 rot times
[ tuck swap join
swap dup + ]
drop
temp put
0 swap
witheach
[ over +
rot 2dup > iff
[ nip swap
0
temp take
i^ poke
temp put ]
else
[ swap rot drop ] ]
- 0 temp take
witheach +
swap ] is egyptian ( n n --> n n )
[ over echo
say " divided by "
dup echo
say " is "
egyptian
swap echo
say " remainder "
echo
say "." ] is task ( n n --> )
580 34 task |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #R | R | Egyptian_division <- function(num, den){
pow2 = 0
row = 1
Table = data.frame(powers_of_2 = 2^pow2,
doubling = den)
while(Table$doubling[nrow(Table)] < num){
row = row + 1
pow2 = pow2 + 1
Table[row, 1] <- 2^pow2
Table[row, 2] <- 2^pow2 * den
}
Table <- Table[-nrow(Table),]
#print(Table) to see the table
answer <- 0
accumulator <- 0
for (i in nrow(Table):1) {
if (accumulator + Table$doubling[i] <= num) {
accumulator <- accumulator + Table$doubling[i]
answer <- answer + Table$powers_of_2[i]
}
}
remainder = abs(accumulator - num)
message(paste0("Answer is ", answer, ", remainder ", remainder))
}
Egyptian_division(580, 34)
Egyptian_division(300, 2)
|
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #Racket | Racket | #lang racket
(define (real->egyptian-list R)
(define (inr r rv)
(match* ((exact-floor r) (numerator r) (denominator r))
[(0 0 1) (reverse rv)]
[(0 1 d) (reverse (cons (/ d) rv))]
[(0 x y) (let ((^y/x (exact-ceiling (/ y x))))
(inr (/ (modulo (- y) x) (* y ^y/x)) (cons (/ ^y/x) rv)))]
[(flr _ _) (inr (- r flr) (cons flr rv))]))
(inr R null))
(define (real->egyptian-string f)
(define e.f.-list (real->egyptian-list f))
(define fmt-part
(match-lambda
[(? integer? (app number->string s)) s]
[(app (compose number->string /) s) (format "/~a"s)]))
(string-join (map fmt-part e.f.-list) " + "))
(define (stat-egyptian-fractions max-b+1)
(define-values (max-l max-l-f max-d max-d-f)
(for*/fold ((max-l 0) (max-l-f #f) (max-d 0) (max-d-f #f))
((b (in-range 1 max-b+1)) (a (in-range 1 b)) #:when (= 1 (gcd a b)))
(define f (/ a b))
(define e.f (real->egyptian-list (/ a b)))
(define l (length e.f))
(define d (denominator (last e.f)))
(values (max max-l l) (if (> l max-l) f max-l-f)
(max max-d d) (if (> d max-d) f max-d-f))))
(printf #<<EOS
max #terms: ~a has ~a
[~.a]
max denominator: ~a has ~a
[~.a]
EOS
max-l-f max-l (real->egyptian-string max-l-f)
max-d-f max-d (real->egyptian-string max-d-f)))
(displayln (real->egyptian-string 43/48))
(displayln (real->egyptian-string 5/121))
(displayln (real->egyptian-string 2014/59))
(newline)
(stat-egyptian-fractions 100)
(newline)
(stat-egyptian-fractions 1000)
(module+ test (require tests/eli-tester)
(test (real->egyptian-list 43/48) => '(1/2 1/3 1/16))) |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #TypeScript | TypeScript |
// Ethiopian multiplication
function intToString(n: number, wdth: number): string {
sn = Math.floor(n).toString();
len = sn.length;
return (wdth < len ? "#".repeat(wdth) : " ".repeat(wdth - len) + sn);
}
function double(a: number): number {
return 2 * a;
}
function halve(a: number): number {
return Math.floor(a / 2);
}
function isEven(a: number): bool {
return a % 2 == 0;
}
function showEthiopianMultiplication(x: number, y: number): void {
var tot = 0;
while (x >= 1) {
process.stdout.write(intToString(x, 9) + " ");
if (!isEven(x)) {
tot += y;
process.stdout.write(intToString(y, 9));
}
console.log();
x = halve(x);
y = double(y);
}
console.log("=" + " ".repeat(9) + intToString(tot, 9));
}
showEthiopianMultiplication(17, 34);
|
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Tcl | Tcl | package require Tcl 8.6
oo::class create ElementaryAutomaton {
variable rules
# Decode the rule number to get a collection of state mapping rules.
# In effect, "compiles" the rule number
constructor {ruleNumber} {
set ins {111 110 101 100 011 010 001 000}
set bits [split [string range [format %08b $ruleNumber] end-7 end] ""]
foreach input {111 110 101 100 011 010 001 000} state $bits {
dict set rules $input $state
}
}
# Apply the rule to an automaton state to get a new automaton state.
# We wrap the edges; the state space is circular.
method evolve {state} {
set len [llength $state]
for {set i 0} {$i < $len} {incr i} {
lappend result [dict get $rules [
lindex $state [expr {($i-1)%$len}]][
lindex $state $i][
lindex $state [expr {($i+1)%$len}]]]
}
return $result
}
# Simple driver method; omit the initial state to get a centred dot
method run {steps {initialState ""}} {
if {[llength [info level 0]] < 4} {
set initialState "[string repeat . $steps]1[string repeat . $steps]"
}
set s [split [string map ". 0 # 1" $initialState] ""]
for {set i 0} {$i < $steps} {incr i} {
puts [string map "0 . 1 #" [join $s ""]]
set s [my evolve $s]
}
puts [string map "0 . 1 #" [join $s ""]]
}
} |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Wortel | Wortel | @fac 10 |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #Raku | Raku | my $socket = IO::Socket::INET.new:
:localhost<localhost>,
:localport<12321>,
:listen;
while $socket.accept -> $conn {
say "Accepted connection";
start {
while $conn.recv -> $stuff {
say "Echoing $stuff";
$conn.print($stuff);
}
$conn.close;
}
} |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #REXX | REXX | /*REXX program to display eban numbers (those that don't have an "e" their English name)*/
numeric digits 20 /*support some gihugic numbers for pgm.*/
parse arg $ /*obtain optional arguments from the cL*/
if $='' then $= '1 1000 1000 4000 1 -10000 1 -100000 1 -1000000 1 -10000000'
do k=1 by 2 to words($) /*step through the list of numbers. */
call banE word($, k), word($, k+1) /*process the numbers, from low──►high.*/
end /*k*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
banE: procedure; parse arg x,y,_; z= reverse(x) /*obtain the number to be examined. */
tell= y>=0 /*Is HI non-negative? Display eban #s.*/
#= 0 /*the count of eban numbers (so far).*/
do j=x to abs(y) /*probably process a range of numbers. */
if hasE(j) then iterate /*determine if the number has an "e". */
#= # + 1 /*bump the counter of eban numbers. */
if tell then _= _ j /*maybe add to a list of eban numbers. */
end /*j*/
if _\=='' then say strip(_) /*display the list (if there is one). */
say; say # ' eban numbers found for: ' x " " y; say copies('═', 105)
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
hasE: procedure; parse arg x; z= reverse(x) /*obtain the number to be examined. */
do k=1 by 3 /*while there're dec. digit to examine.*/
@= reverse( substr(z, k, 3) ) /*obtain 3 dec. digs (a period) from Z.*/
if @==' ' then return 0 /*we have reached the "end" of the num.*/
uni= right(@, 1) /*get units dec. digit of this period. */
if uni//2==1 then return 1 /*if an odd digit, then not an eban #. */
if uni==8 then return 1 /*if an eight, " " " " " */
tens=substr(@, 2, 1) /*get tens dec. digit of this period. */
if tens==1 then return 1 /*if teens, then not an eban #. */
if tens==2 then return 1 /*if twenties, " " " " " */
if tens>6 then return 1 /*if 70s, 80s, 90s, " " " " " */
hun= left(@, 1) /*get hundreds dec. dig of this period.*/
if hun==0 then iterate /*if zero, then there is more of number*/
if hun\==' ' then return 1 /*any hundrEd (not zero) has an "e". */
end /*k*/ /*A "period" is a group of 3 dec. digs */
return 0 /*in the number, grouped from the right*/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.