Skip to content

Commit 7b4c4ad

Browse files
committed
Add three examples for B from rosettacode.
1 parent 51719d7 commit 7b4c4ad

File tree

3 files changed

+107
-0
lines changed

3 files changed

+107
-0
lines changed

examples/doors.dub

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
*name B compiler
2+
* Example from rosettacode.org/wiki/100_doors#B
3+
*tape:7/b,40
4+
*library:40
5+
*trans-main:40020
6+
main()
7+
{
8+
auto doors[100]; /* != 0 means open */
9+
auto pass, door;
10+
11+
door = 0;
12+
while (door < 100)
13+
doors[door++] = 0;
14+
15+
pass = 0;
16+
while (pass < 100) {
17+
door = pass;
18+
while (door < 100) {
19+
doors[door] = !doors[door];
20+
door = door + pass + 1;
21+
}
22+
++pass;
23+
}
24+
25+
door = 0;
26+
while (door < 100) {
27+
printf("door #%d is %s.*n", door+1, doors[door] ? "open" : "closed");
28+
++door;
29+
}
30+
}
31+
*execute
32+
*end file

examples/isprime.dub

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
*name B compiler
2+
* Example from rosettacode.org/wiki/Primality_by_trial_division#B
3+
*tape:7/b,40
4+
*library:40
5+
*trans-main:40020
6+
isprime(n) {
7+
auto p;
8+
9+
if (n < 2)
10+
return (0);
11+
if (!(n % 2))
12+
return (n == 2);
13+
p = 3;
14+
while (n / p > p) {
15+
if (!(n % p))
16+
return(0);
17+
p = p + 2;
18+
}
19+
return (1);
20+
}
21+
22+
test(n) {
23+
printf("%d is %s*n", n, isprime(n) ? "prime" : "not prime");
24+
}
25+
26+
main() {
27+
test(42);
28+
test(43);
29+
}
30+
*execute
31+
*end file

examples/mandelbrot.b

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
main() {
2+
auto cx, cy, x, y, x2, y2;
3+
auto iter;
4+
auto xmin, xmax, ymin, ymax, maxiter, dx, dy;
5+
6+
xmin = -8601;
7+
xmax = 2867;
8+
ymin = -4915;
9+
ymax = 4915;
10+
11+
maxiter = 32;
12+
13+
dx = (xmax - xmin) / 79;
14+
dy = (ymax - ymin) / 24;
15+
16+
cy = ymin;
17+
while (cy <= ymax) {
18+
cx = xmin;
19+
while (cx <= xmax) {
20+
x = 0;
21+
y = 0;
22+
x2 = 0;
23+
y2 = 0;
24+
iter = 0;
25+
while (iter < maxiter) {
26+
if (x2 + y2 > 16384)
27+
break;
28+
29+
y = ((x * y) >> 11) + cy;
30+
x = x2 - y2 + cx;
31+
x2 = (x * x) >> 12;
32+
y2 = (y * y) >> 12;
33+
iter++;
34+
}
35+
putchar(' ' + iter);
36+
cx = cx + dx;
37+
}
38+
putchar(13);
39+
putchar(10);
40+
cy = cy + dy;
41+
}
42+
43+
return(0);
44+
}

0 commit comments

Comments
 (0)