Update formatting to consistently use tabs.

This commit is contained in:
Christoffer Lerno
2022-02-18 12:56:17 +01:00
parent bf5683b41c
commit 6b4e4f6114
10 changed files with 422 additions and 434 deletions

View File

@@ -4,37 +4,37 @@ module base64;
errtype DecodingError errtype DecodingError
{ {
INVALID_CHARACTER INVALID_CHARACTER
} }
const char[64] LUT_ENC = { const char[64] LUT_ENC = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/', '4', '5', '6', '7', '8', '9', '+', '/',
}; };
const char ERR = 0xFF; const char ERR = 0xFF;
const char[256] LUT_DEC = const char[256] LUT_DEC =
{ {
[0..255] = ERR, [0..255] = ERR,
['A'] = 0, ['B'] = 1, ['C'] = 2, ['D'] = 3, ['E'] = 4, ['A'] = 0, ['B'] = 1, ['C'] = 2, ['D'] = 3, ['E'] = 4,
['F'] = 5, ['G'] = 6, ['H'] = 7, ['I'] = 8, ['J'] = 9, ['F'] = 5, ['G'] = 6, ['H'] = 7, ['I'] = 8, ['J'] = 9,
['K'] = 10, ['L'] = 11, ['M'] = 12, ['N'] = 13, ['O'] = 14, ['K'] = 10, ['L'] = 11, ['M'] = 12, ['N'] = 13, ['O'] = 14,
['P'] = 15, ['Q'] = 16, ['R'] = 17, ['S'] = 18, ['T'] = 19, ['P'] = 15, ['Q'] = 16, ['R'] = 17, ['S'] = 18, ['T'] = 19,
['U'] = 20, ['V'] = 21, ['W'] = 22, ['X'] = 23, ['Y'] = 24, ['U'] = 20, ['V'] = 21, ['W'] = 22, ['X'] = 23, ['Y'] = 24,
['Z'] = 25, ['a'] = 26, ['b'] = 27, ['c'] = 28, ['d'] = 29, ['Z'] = 25, ['a'] = 26, ['b'] = 27, ['c'] = 28, ['d'] = 29,
['e'] = 30, ['f'] = 31, ['g'] = 32, ['h'] = 33, ['i'] = 34, ['e'] = 30, ['f'] = 31, ['g'] = 32, ['h'] = 33, ['i'] = 34,
['j'] = 35, ['k'] = 36, ['l'] = 37, ['m'] = 38, ['n'] = 39, ['j'] = 35, ['k'] = 36, ['l'] = 37, ['m'] = 38, ['n'] = 39,
['o'] = 40, ['p'] = 41, ['q'] = 42, ['r'] = 43, ['s'] = 44, ['o'] = 40, ['p'] = 41, ['q'] = 42, ['r'] = 43, ['s'] = 44,
['t'] = 45, ['u'] = 46, ['v'] = 47, ['w'] = 48, ['x'] = 49, ['t'] = 45, ['u'] = 46, ['v'] = 47, ['w'] = 48, ['x'] = 49,
['y'] = 50, ['z'] = 51, ['0'] = 52, ['1'] = 53, ['2'] = 54, ['y'] = 50, ['z'] = 51, ['0'] = 52, ['1'] = 53, ['2'] = 54,
['3'] = 55, ['4'] = 56, ['5'] = 57, ['6'] = 58, ['7'] = 59, ['3'] = 55, ['4'] = 56, ['5'] = 57, ['6'] = 58, ['7'] = 59,
['8'] = 60, ['9'] = 61, ['+'] = 62, ['/'] = 63 ['8'] = 60, ['9'] = 61, ['+'] = 62, ['/'] = 63
}; };
@@ -45,90 +45,90 @@ const char LAST = 'z';
fn void encode(char[] in, char *out) fn void encode(char[] in, char *out)
{ {
int j = 0; int j = 0;
char c = LUT_ENC[1]; char c = LUT_ENC[1];
for (int i = 0; i < in.len; i++) for (int i = 0; i < in.len; i++)
{ {
switch (i % 3) switch (i % 3)
{ {
case 0: case 0:
out[j++] = LUT_ENC[(in[i] >> 2) & 0x3F]; out[j++] = LUT_ENC[(in[i] >> 2) & 0x3F];
case 1: case 1:
out[j++] = LUT_ENC[(in[i - 1] & 0x3) << 4 + ((in[i] >> 4) & 0xF)]; out[j++] = LUT_ENC[(in[i - 1] & 0x3) << 4 + ((in[i] >> 4) & 0xF)];
case 2: case 2:
out[j++] = LUT_ENC[(in[i - 1] & 0xF) << 2 + ((in[i] >> 6) & 0x3)]; out[j++] = LUT_ENC[(in[i - 1] & 0xF) << 2 + ((in[i] >> 6) & 0x3)];
out[j++] = LUT_ENC[in[i] & 0x3F]; out[j++] = LUT_ENC[in[i] & 0x3F];
} }
} }
// move back // move back
usize last = in.len - 1; usize last = in.len - 1;
// check the last and add padding // check the last and add padding
switch (last % 3) switch (last % 3)
{ {
case 0: case 0:
out[j++] = LUT_ENC[(in[last] & 0x3) << 4]; out[j++] = LUT_ENC[(in[last] & 0x3) << 4];
out[j++] = PAD; out[j++] = PAD;
out[j++] = PAD; out[j++] = PAD;
case 1: case 1:
out[j++] = LUT_ENC[(in[last] & 0xF) << 2]; out[j++] = LUT_ENC[(in[last] & 0xF) << 2];
out[j++] = PAD; out[j++] = PAD;
} }
} }
fn int! decode(char[] in, char* out, int* invalid_char_index = null) fn int! decode(char[] in, char* out, int* invalid_char_index = null)
{ {
int j = 0; int j = 0;
for (int i = 0; i < in.len; i++) for (int i = 0; i < in.len; i++)
{ {
char value = in[i]; char value = in[i];
if (value == PAD) return j; if (value == PAD) return j;
char c = LUT_DEC[in[i]]; char c = LUT_DEC[in[i]];
if (c == ERR) if (c == ERR)
{ {
if (invalid_char_index) *invalid_char_index = i; if (invalid_char_index) *invalid_char_index = i;
return DecodingError.INVALID_CHARACTER!; return DecodingError.INVALID_CHARACTER!;
} }
switch (i % 4) switch (i % 4)
{ {
case 0: case 0:
out[j] = c << 2; out[j] = c << 2;
case 1: case 1:
out[j++] += c >> 4 & 0x3; out[j++] += c >> 4 & 0x3;
// if not last char with padding // if not last char with padding
if (i < (in.len - 3) || in[(long)(in.len) - 2] != PAD) if (i < (in.len - 3) || in[(long)(in.len) - 2] != PAD)
{ {
out[j] = (c & 0xF) << 4; out[j] = (c & 0xF) << 4;
} }
case 2: case 2:
out[j++] += c >> 2 & 0xF; out[j++] += c >> 2 & 0xF;
if (i < (in.len - 2) || in[(long)(in.len) - 1] != PAD) if (i < (in.len - 2) || in[(long)(in.len) - 1] != PAD)
{ {
out[j] = (c & 0x3) << 6; out[j] = (c & 0x3) << 6;
} }
case 3: case 3:
out[j++] += c; out[j++] += c;
} }
} }
return j; return j;
} }
extern fn void printf(char *fmt, ...); extern fn void printf(char *fmt, ...);
fn void main() fn void main()
{ {
char *helloworld = "Hello World\n"; char *helloworld = "Hello World\n";
char[1000] buffer; char[1000] buffer;
encode(helloworld[0..12], &buffer); encode(helloworld[0..12], &buffer);
printf("Result: %s\n", &buffer); printf("Result: %s\n", &buffer);
char *to_decode = "aGVsbG8gd29ybGRcMA=="; char *to_decode = "aGVsbG8gd29ybGRcMA==";
char[*] result = b64"aGVsbG8gd29ybGRcMA=="; char[*] result = b64"aGVsbG8gd29ybGRcMA==";
decode(to_decode[0..19], &buffer); decode(to_decode[0..19], &buffer);
printf("Result: %s\n", &buffer); printf("Result: %s\n", &buffer);
printf("Result direct: %.*s\n", 13, &result); printf("Result direct: %.*s\n", 13, &result);
} }

View File

@@ -1,16 +1,16 @@
macro int factorial($n) macro int factorial($n)
{ {
$if ($n == 0): $if ($n == 0):
return 1; return 1;
$else: $else:
return $n * @factorial($n - 1); return $n * @factorial($n - 1);
$endif; $endif;
} }
extern fn void printf(char *fmt, ...); extern fn void printf(char *fmt, ...);
fn void main() fn void main()
{ {
int x = @factorial(12); int x = @factorial(12);
printf("12! = %d\n", x); printf("12! = %d\n", x);
} }

View File

@@ -5,76 +5,76 @@ import std::mem;
macro int max(int a, int b) macro int max(int a, int b)
{ {
return a > b ? a : b; return a > b ? a : b;
} }
fn int fannkuchredux(int n) fn int fannkuchredux(int n)
{ {
int* perm = @array::make(int, n); int* perm = @array::make(int, n);
int* perm1 = @array::make(int, n); int* perm1 = @array::make(int, n);
int* count = @array::make(int, n); int* count = @array::make(int, n);
int max_flips_count; int max_flips_count;
int perm_count; int perm_count;
int checksum; int checksum;
for (int i = 0; i < n; i++) perm1[i] = i; for (int i = 0; i < n; i++) perm1[i] = i;
int r = n; int r = n;
while (1) while (1)
{ {
for (; r != 1; r--) count[r - 1] = r; for (; r != 1; r--) count[r - 1] = r;
for (int i = 0; i < n; i++) perm[i] = perm1[i]; for (int i = 0; i < n; i++) perm[i] = perm1[i];
int flips_count = 0; int flips_count = 0;
int k; int k;
while (!((k = perm[0]) == 0)) while (!((k = perm[0]) == 0))
{ {
int k2 = (k + 1) >> 1; int k2 = (k + 1) >> 1;
for (int i = 0; i < k2; i++) for (int i = 0; i < k2; i++)
{ {
int temp = perm[i]; int temp = perm[i];
perm[i] = perm[k - i]; perm[i] = perm[k - i];
perm[k - i] = temp; perm[k - i] = temp;
} }
flips_count++; flips_count++;
} }
max_flips_count = @max(max_flips_count, flips_count); max_flips_count = @max(max_flips_count, flips_count);
checksum += perm_count % 2 == 0 ? flips_count : -flips_count; checksum += perm_count % 2 == 0 ? flips_count : -flips_count;
/* Use incremental change to generate another permutation */ /* Use incremental change to generate another permutation */
while (1) while (1)
{ {
if (r == n) if (r == n)
{ {
libc::printf("%d\n", checksum); libc::printf("%d\n", checksum);
return max_flips_count; return max_flips_count;
} }
int perm0 = perm1[0]; int perm0 = perm1[0];
int i = 0; int i = 0;
while (i < r) while (i < r)
{ {
int j = i + 1; int j = i + 1;
perm1[i] = perm1[j]; perm1[i] = perm1[j];
i = j; i = j;
} }
perm1[r] = perm0; perm1[r] = perm0;
count[r] = count[r] - 1; count[r] = count[r] - 1;
if (count[r] > 0) break; if (count[r] > 0) break;
r++; r++;
} }
perm_count++; perm_count++;
} }
return 0; return 0;
} }
fn int main(int argc, char** argv) fn int main(int argc, char** argv)
{ {
int n = argc > 1 ? libc::atoi(argv[1]) : 7; int n = argc > 1 ? libc::atoi(argv[1]) : 7;
libc::printf("Pfannkuchen(%d) = %d\n", n, fannkuchredux(n)); libc::printf("Pfannkuchen(%d) = %d\n", n, fannkuchredux(n));
return 0; return 0;
} }

View File

@@ -15,39 +15,39 @@ fn float fasta_rand(float max)
} }
private char[] alu = private char[] alu =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG"
"GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA"
"CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT"
"ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA"
"GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG"
"AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC"
"AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
char[] iub = "acgtBDHKMNRSVWY"; char[] iub = "acgtBDHKMNRSVWY";
double[] iub_p = { double[] iub_p = {
0.27, 0.27,
0.12, 0.12,
0.12, 0.12,
0.27, 0.27,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02, 0.02,
0.02 }; 0.02 };
char[] homosapiens = "acgt"; char[] homosapiens = "acgt";
double[] homosapiens_p = { double[] homosapiens_p = {
0.3029549426680, 0.3029549426680,
0.1979883004921, 0.1979883004921,
0.1975473066391, 0.1975473066391,
0.3015094502008 0.3015094502008
}; };
const LINELEN = 60; const LINELEN = 60;

View File

@@ -11,10 +11,10 @@ extern fn void usleep(int time);
struct GameBoard struct GameBoard
{ {
int h; int h;
int w; int w;
char* world; char* world;
char* temp; char* temp;
} }
fn void GameBoard.show(GameBoard *board) fn void GameBoard.show(GameBoard *board)
@@ -24,11 +24,11 @@ fn void GameBoard.show(GameBoard *board)
char* current = board.world; char* current = board.world;
for (int y = 0; y < board.h; y++) for (int y = 0; y < board.h; y++)
{ {
for (int x = 0; x < board.w; x++) for (int x = 0; x < board.w; x++)
{ {
printf(*current ? "\e[07m \e[m" : " "); printf(*current ? "\e[07m \e[m" : " ");
current++; current++;
} }
printf("\e[E"); printf("\e[E");
} }
fflush(__stdoutp); fflush(__stdoutp);
@@ -38,25 +38,25 @@ fn void GameBoard.evolve(GameBoard *board)
{ {
for (int y = 0; y < board.h; y++) for (int y = 0; y < board.h; y++)
{ {
for (int x = 0; x < board.w; x++) for (int x = 0; x < board.w; x++)
{ {
int n = 0; int n = 0;
for (int y1 = y - 1; y1 <= y + 1; y1++) for (int y1 = y - 1; y1 <= y + 1; y1++)
{ {
for (int x1 = x - 1; x1 <= x + 1; x1++) for (int x1 = x - 1; x1 <= x + 1; x1++)
{ {
int actualX = (x1 + board.w) % board.w; int actualX = (x1 + board.w) % board.w;
int actualY = (y1 + board.h) % board.h; int actualY = (y1 + board.h) % board.h;
if (board.world[actualX + actualY * board.w]) n++; if (board.world[actualX + actualY * board.w]) n++;
} }
} }
if (board.world[x + y * board.w]) n--; if (board.world[x + y * board.w]) n--;
board.temp[x + y * board.w] = (char)(n == 3 || (n == 2 && board.world[x + y * board.w])); board.temp[x + y * board.w] = (char)(n == 3 || (n == 2 && board.world[x + y * board.w]));
} }
} }
for (int i = 0; i < board.w * board.h; i++) for (int i = 0; i < board.w * board.h; i++)
{ {
board.world[i] = board.temp[i]; board.world[i] = board.temp[i];
} }
} }
@@ -70,17 +70,17 @@ fn int main(int c, char** v)
if (w <= 0) w = 30; if (w <= 0) w = 30;
if (h <= 0) h = 30; if (h <= 0) h = 30;
GameBoard board; GameBoard board;
board.w = w; board.w = w;
board.h = h; board.h = h;
board.world = malloc((ulong)(h * w)); board.world = malloc((ulong)(h * w));
board.temp = malloc((ulong)(h * w)); board.temp = malloc((ulong)(h * w));
for (int i = h * w - 1; i >= 0; i--) for (int i = h * w - 1; i >= 0; i--)
{ {
board.world[i] = rand() % 10 == 0 ? 1 : 0; board.world[i] = rand() % 10 == 0 ? 1 : 0;
} }
for (int j = 0; j < 1000; j++) for (int j = 0; j < 1000; j++)
{ {
board.show(); board.show();
board.evolve(); board.evolve();

View File

@@ -8,88 +8,88 @@ extern fn isize getline(char** linep, usize* linecapp, CFile stream);
struct Game struct Game
{ {
int answer; int answer;
bool done; bool done;
int guesses; int guesses;
int high; int high;
} }
optnum InputResult optnum InputResult
{ {
NOT_AN_INT, NOT_AN_INT,
FAILED_TO_READ, FAILED_TO_READ,
} }
int err_count = 0; int err_count = 0;
fn int! askGuess(int high) fn int! askGuess(int high)
{ {
printf("Guess a number between 1 and %d: ", high); printf("Guess a number between 1 and %d: ", high);
char[] text = readLine()?; char[] text = readLine()?;
char* end = null; char* end = null;
int value = (int)libc::strtol(text.ptr, &end, 10); int value = (int)libc::strtol(text.ptr, &end, 10);
if (end && end[0] >= ' ') return InputResult.NOT_AN_INT!; if (end && end[0] >= ' ') return InputResult.NOT_AN_INT!;
return value; return value;
} }
fn char[]! readLine() fn char[]! readLine()
{ {
char* chars = mem::talloc(1024)?; char* chars = mem::talloc(1024)?;
isize loaded = getline(&chars, &&(usize)1023, @libc::stdin()); isize loaded = getline(&chars, &&(usize)1023, @libc::stdin());
if (loaded < 0) return InputResult.FAILED_TO_READ!; if (loaded < 0) return InputResult.FAILED_TO_READ!;
chars[loaded] = 0; chars[loaded] = 0;
return chars[0..(loaded - 1)]; return chars[0..(loaded - 1)];
} }
fn int! askGuessMulti(int high) fn int! askGuessMulti(int high)
{ {
while (true) while (true)
{ {
int! result = askGuess(high); int! result = askGuess(high);
if (catch(result) == InputResult.NOT_AN_INT) if (catch(result) == InputResult.NOT_AN_INT)
{ {
printf("I didn't understand that.\n"); printf("I didn't understand that.\n");
err_count++; err_count++;
continue; continue;
} }
return result; return result;
} }
$unreachable; $unreachable;
} }
fn void! Game.play(Game *game) fn void! Game.play(Game *game)
{ {
while (!game.done) while (!game.done)
{ {
int guess = askGuessMulti(game.high)?; int guess = askGuessMulti(game.high)?;
game.report(guess); game.report(guess);
game.update(guess); game.update(guess);
} }
} }
fn void Game.report(Game *game, int guess) fn void Game.report(Game *game, int guess)
{ {
char[] desc = {| char[] desc = {|
if (guess < game.answer) return "too low"; if (guess < game.answer) return "too low";
if (guess > game.answer) return "too high"; if (guess > game.answer) return "too high";
return "the answer"; return "the answer";
|}; |};
printf("%d is %.*s.\n", guess, (int)desc.len, desc.ptr); printf("%d is %.*s.\n", guess, (int)desc.len, desc.ptr);
} }
fn void Game.update(Game *game, int guess) fn void Game.update(Game *game, int guess)
{ {
if (guess == game.answer) game.done = true; if (guess == game.answer) game.done = true;
game.guesses++; game.guesses++;
} }
fn void! main() fn void! main()
{ {
libc::srand((int)libc::clock()); libc::srand((int)libc::clock());
int high = 100; int high = 100;
int answer = libc::rand() % high + 1; int answer = libc::rand() % high + 1;
Game game = { .answer = answer, .high = high }; Game game = { .answer = answer, .high = high };
game.play(); game.play();
printf("Finished in %d guesses.\n", game.guesses); printf("Finished in %d guesses.\n", game.guesses);
printf("Total input errors: %d.\n", err_count); printf("Total input errors: %d.\n", err_count);
} }

View File

@@ -4,23 +4,23 @@ import std::math;
// This levenshtein exercises C3 subarrays. // This levenshtein exercises C3 subarrays.
fn int levenshtein(char[] s, char[] t) fn int levenshtein(char[] s, char[] t)
{ {
// if either string is empty, difference is inserting all chars // if either string is empty, difference is inserting all chars
// from the other // from the other
if (!s.len) return t.len; if (!s.len) return t.len;
if (!t.len) return s.len; if (!t.len) return s.len;
// if last letters are the same, the difference is whatever is // if last letters are the same, the difference is whatever is
// required to edit the rest of the strings // required to edit the rest of the strings
if (s[^1] == t[^1]) return levenshtein(s[0..^2], t[0..^2]); if (s[^1] == t[^1]) return levenshtein(s[0..^2], t[0..^2]);
// else try: // else try:
// changing last letter of s to that of t; or // changing last letter of s to that of t; or
// remove last letter of s; or // remove last letter of s; or
// remove last letter of t, // remove last letter of t,
// any of which is 1 edit plus editing the rest of the strings // any of which is 1 edit plus editing the rest of the strings
int a = levenshtein(s[0..^2], t[0..^2]); int a = levenshtein(s[0..^2], t[0..^2]);
int b = levenshtein(s, t[0..^2]); int b = levenshtein(s, t[0..^2]);
int c = levenshtein(s[0..^2], t); int c = levenshtein(s[0..^2], t);
return @min(@min(a, b), c) + 1; return @min(@min(a, b), c) + 1;
} }

View File

@@ -8,116 +8,116 @@ const RECIP_DT = (1.0/DT);
struct Planet struct Planet
{ {
double x, y, z; double x, y, z;
double vx, vy, vz; double vx, vy, vz;
double mass; double mass;
} }
fn void advance(Planet[] bodies) @noinline fn void advance(Planet[] bodies) @noinline
{ {
usize nbodies = bodies.len; usize nbodies = bodies.len;
foreach (i, Planet* &b : bodies) foreach (i, Planet* &b : bodies)
{ {
for (usize j = i + 1; j < nbodies; j++) for (usize j = i + 1; j < nbodies; j++)
{ {
Planet* b2 = &bodies[j]; Planet* b2 = &bodies[j];
double dx = b.x - b2.x; double dx = b.x - b2.x;
double dy = b.y - b2.y; double dy = b.y - b2.y;
double dz = b.z - b2.z; double dz = b.z - b2.z;
double inv_distance = 1.0/sqrt(dx * dx + dy * dy + dz * dz); double inv_distance = 1.0/sqrt(dx * dx + dy * dy + dz * dz);
double mag = inv_distance * inv_distance * inv_distance; double mag = inv_distance * inv_distance * inv_distance;
b.vx -= dx * b2.mass * mag; b.vx -= dx * b2.mass * mag;
b.vy -= dy * b2.mass * mag; b.vy -= dy * b2.mass * mag;
b.vz -= dz * b2.mass * mag; b.vz -= dz * b2.mass * mag;
b2.vx += dx * b.mass * mag; b2.vx += dx * b.mass * mag;
b2.vy += dy * b.mass * mag; b2.vy += dy * b.mass * mag;
b2.vz += dz * b.mass * mag; b2.vz += dz * b.mass * mag;
} }
} }
foreach (&b : bodies) foreach (&b : bodies)
{ {
b.x += b.vx; b.x += b.vx;
b.y += b.vy; b.y += b.vy;
b.z += b.vz; b.z += b.vz;
} }
} }
fn double energy(Planet[] bodies) fn double energy(Planet[] bodies)
{ {
double e; double e;
usize nbodies = bodies.len; usize nbodies = bodies.len;
foreach (i, Planet* &b : bodies) foreach (i, Planet* &b : bodies)
{ {
e += 0.5 * b.mass * (b.vx * b.vx + b.vy * b.vy + b.vz * b.vz); e += 0.5 * b.mass * (b.vx * b.vx + b.vy * b.vy + b.vz * b.vz);
for (usize j = i + 1; j < nbodies; j++) for (usize j = i + 1; j < nbodies; j++)
{ {
Planet* b2 = &bodies[j]; Planet* b2 = &bodies[j];
double dx = b.x - b2.x; double dx = b.x - b2.x;
double dy = b.y - b2.y; double dy = b.y - b2.y;
double dz = b.z - b2.z; double dz = b.z - b2.z;
double distance = sqrt(dx * dx + dy * dy + dz * dz); double distance = sqrt(dx * dx + dy * dy + dz * dz);
e -= (b.mass * b2.mass) / distance; e -= (b.mass * b2.mass) / distance;
} }
} }
return e; return e;
} }
fn void offset_momentum(Planet[] bodies) fn void offset_momentum(Planet[] bodies)
{ {
double px; double px;
double py; double py;
double pz; double pz;
foreach (&b : bodies) foreach (&b : bodies)
{ {
px += b.vx * b.mass; px += b.vx * b.mass;
py += b.vy * b.mass; py += b.vy * b.mass;
pz += b.vz * b.mass; pz += b.vz * b.mass;
} }
bodies[0].vx = - px / SOLAR_MASS; bodies[0].vx = - px / SOLAR_MASS;
bodies[0].vy = - py / SOLAR_MASS; bodies[0].vy = - py / SOLAR_MASS;
bodies[0].vz = - pz / SOLAR_MASS; bodies[0].vz = - pz / SOLAR_MASS;
} }
Planet[*] planet_bodies = { Planet[*] planet_bodies = {
{ /* sun */ { /* sun */
0, 0, 0, 0, 0, 0, SOLAR_MASS 0, 0, 0, 0, 0, 0, SOLAR_MASS
}, },
{ /* jupiter */ { /* jupiter */
4.84143144246472090e+00, 4.84143144246472090e+00,
-1.16032004402742839e+00, -1.16032004402742839e+00,
-1.03622044471123109e-01, -1.03622044471123109e-01,
1.66007664274403694e-03 * DAYS_PER_YEAR, 1.66007664274403694e-03 * DAYS_PER_YEAR,
7.69901118419740425e-03 * DAYS_PER_YEAR, 7.69901118419740425e-03 * DAYS_PER_YEAR,
-6.90460016972063023e-05 * DAYS_PER_YEAR, -6.90460016972063023e-05 * DAYS_PER_YEAR,
9.54791938424326609e-04 * SOLAR_MASS 9.54791938424326609e-04 * SOLAR_MASS
}, },
{ /* saturn */ { /* saturn */
8.34336671824457987e+00, 8.34336671824457987e+00,
4.12479856412430479e+00, 4.12479856412430479e+00,
-4.03523417114321381e-01, -4.03523417114321381e-01,
-2.76742510726862411e-03 * DAYS_PER_YEAR, -2.76742510726862411e-03 * DAYS_PER_YEAR,
4.99852801234917238e-03 * DAYS_PER_YEAR, 4.99852801234917238e-03 * DAYS_PER_YEAR,
2.30417297573763929e-05 * DAYS_PER_YEAR, 2.30417297573763929e-05 * DAYS_PER_YEAR,
2.85885980666130812e-04 * SOLAR_MASS 2.85885980666130812e-04 * SOLAR_MASS
}, },
{ /* uranus */ { /* uranus */
1.28943695621391310e+01, 1.28943695621391310e+01,
-1.51111514016986312e+01, -1.51111514016986312e+01,
-2.23307578892655734e-01, -2.23307578892655734e-01,
2.96460137564761618e-03 * DAYS_PER_YEAR, 2.96460137564761618e-03 * DAYS_PER_YEAR,
2.37847173959480950e-03 * DAYS_PER_YEAR, 2.37847173959480950e-03 * DAYS_PER_YEAR,
-2.96589568540237556e-05 * DAYS_PER_YEAR, -2.96589568540237556e-05 * DAYS_PER_YEAR,
4.36624404335156298e-05 * SOLAR_MASS 4.36624404335156298e-05 * SOLAR_MASS
}, },
{ /* neptune */ { /* neptune */
1.53796971148509165e+01, 1.53796971148509165e+01,
-2.59193146099879641e+01, -2.59193146099879641e+01,
1.79258772950371181e-01, 1.79258772950371181e-01,
2.68067772490389322e-03 * DAYS_PER_YEAR, 2.68067772490389322e-03 * DAYS_PER_YEAR,
1.62824170038242295e-03 * DAYS_PER_YEAR, 1.62824170038242295e-03 * DAYS_PER_YEAR,
-9.51592254519715870e-05 * DAYS_PER_YEAR, -9.51592254519715870e-05 * DAYS_PER_YEAR,
5.15138902046611451e-05 * SOLAR_MASS 5.15138902046611451e-05 * SOLAR_MASS
} }
}; };
@@ -130,13 +130,13 @@ Planet[*] planet_bodies = {
*/ */
fn void scale_bodies(Planet[] bodies, double scale) fn void scale_bodies(Planet[] bodies, double scale)
{ {
foreach (&b : bodies) foreach (&b : bodies)
{ {
b.mass *= scale * scale; b.mass *= scale * scale;
b.vx *= scale; b.vx *= scale;
b.vy *= scale; b.vy *= scale;
b.vz *= scale; b.vz *= scale;
} }
} }
extern fn int atoi(char *s); extern fn int atoi(char *s);
@@ -145,17 +145,17 @@ extern fn double sqrt(double);
fn int main(int argc, char ** argv) fn int main(int argc, char ** argv)
{ {
int n = atoi(argv[1]); int n = atoi(argv[1]);
Planet[] bodies = &planet_bodies; Planet[] bodies = &planet_bodies;
offset_momentum(bodies); offset_momentum(bodies);
printf ("%.9f\n", energy(bodies)); printf ("%.9f\n", energy(bodies));
scale_bodies(bodies, DT); scale_bodies(bodies, DT);
for (int i = 1; i <= n; i++) for (int i = 1; i <= n; i++)
{ {
advance(bodies); advance(bodies);
} }
scale_bodies(bodies, RECIP_DT); scale_bodies(bodies, RECIP_DT);
printf ("%.9f\n", energy(bodies)); printf ("%.9f\n", energy(bodies));
return 0; return 0;
} }

View File

@@ -18,10 +18,10 @@ fn void eval_A_times_u(double[] u, double[] au)
foreach (i, &val : au) foreach (i, &val : au)
{ {
*val = 0; *val = 0;
foreach (j, uval : u) foreach (j, uval : u)
{ {
*val += eval_A((int)(i), (int)(j)) * uval; *val += eval_A((int)(i), (int)(j)) * uval;
} }
} }
} }
@@ -30,10 +30,10 @@ fn void eval_At_times_u(double[] u, double[] au)
foreach (i, &val : au) foreach (i, &val : au)
{ {
*val = 0; *val = 0;
foreach (j, uval : u) foreach (j, uval : u)
{ {
*val += eval_A((int)(j), (int)(i)) * uval; *val += eval_A((int)(j), (int)(i)) * uval;
} }
} }
} }
@@ -47,21 +47,21 @@ fn int main(int argc, char **argv)
{ {
int n = (argc == 2) ? atoi(argv[1]) : 2000; int n = (argc == 2) ? atoi(argv[1]) : 2000;
temparr = @array::make(double, n); temparr = @array::make(double, n);
double[] u = @array::make(double, n); double[] u = @array::make(double, n);
double[] v = @array::make(double, n); double[] v = @array::make(double, n);
foreach(&uval : u) *uval = 1; foreach(&uval : u) *uval = 1;
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
eval_AtA_times_u(u, v); eval_AtA_times_u(u, v);
eval_AtA_times_u(v, u); eval_AtA_times_u(v, u);
} }
double vBv; double vBv;
double vv; double vv;
foreach (i, vval : v) foreach (i, vval : v)
{ {
vBv += u[i] * vval; vBv += u[i] * vval;
vv += vval * vval; vv += vval * vval;
} }
printf("%0.9f\n", sqrt(vBv / vv)); printf("%0.9f\n", sqrt(vBv / vv));
return 0; return 0;
} }

View File

@@ -49,16 +49,21 @@ static inline void backtrace_to_lexing_start(Lexer *lexer)
} }
// Peek at the current character in the buffer. // Peek at the current character in the buffer.
static inline char peek(Lexer *lexer) #define peek(lexer_) (*(lexer_)->current)
{
return *lexer->current;
}
// Look at the prev character in the buffer. // Look at the prev character in the buffer.
static inline char prev(Lexer *lexer) #define prev(lexer_) ((lexer_)->current[-1])
{
return lexer->current[-1]; // Peek one character ahead.
} #define peek_next(lexer_) ((lexer_)->current[1])
// Is the current character '\0' if so we assume we reached the end.
#define reached_end(lexer_) (lexer_->current[0] == '\0')
// Return the current character and step one character forward.
#define next(lexer_) \
(((lexer_)->current[0] == '\n' ? ((lexer_)->line_start = (lexer_)->current + 1, (lexer_)->current_row++) : false), \
(lexer_)->current++)
// Backtrack the buffer read one step. // Backtrack the buffer read one step.
static inline void backtrack(Lexer *lexer) static inline void backtrack(Lexer *lexer)
@@ -70,22 +75,8 @@ static inline void backtrack(Lexer *lexer)
} }
} }
// Peek one character ahead.
static inline char peek_next(Lexer *lexer)
{
return lexer->current[1];
}
// Return the current character and step one character forward.
static inline void next(Lexer *lexer)
{
if (lexer->current[0] == '\n')
{
lexer->line_start = lexer->current + 1;
lexer->current_row++;
}
lexer->current++;
}
// Skip the x next characters. // Skip the x next characters.
static inline void skip(Lexer *lexer, int steps) static inline void skip(Lexer *lexer, int steps)
@@ -97,13 +88,10 @@ static inline void skip(Lexer *lexer, int steps)
} }
} }
// Is the current character '\0' if so we assume we reached the end.
static inline bool reached_end(Lexer *lexer)
{
return *lexer->current == '\0';
}
// Match a single character if successful, more one step forward. // Match a single character if successful, more one step forward.
static inline bool match(Lexer *lexer, char expected) static inline bool match(Lexer *lexer, char expected)
{ {
if (lexer->current[0] != expected) return false; if (lexer->current[0] != expected) return false;