Beneath each snippet is a link to a gist containing my other solutions
Nota Bene: Code here is factored for fun and beauty. Best practices are cast to the wind with gleeful abandon.
Instead of the conventional backtracking approach, this is a pure, functional implementation with no global state.
var {range} = require('range')
function isThreatened(board, pos) {
return board.includes(pos) ||
board.filter((e, i, a) =>
a.length - i === Math.abs(e - pos)
).length
}
function nqueens(n, board=[]) {
let moves = range(n).filter(e=>
!isThreatened(board, e)
)
return board.length === n - 1
? moves
: moves.map((m, i, a)=>
nqueens(n, a.concat([m])).map(sol=>
[m].concat(sol)
)
).reduce((acc, cur) => acc.concat(cur), []);
}
console.log(nqueens(8))
Below is my solution in Elixir. The Scheme version uses a macro so you can enter the time as-is. So : instead of the string literal ":" (like my Python version) or three integers like the version below.
defmodule ClockAngle do
def pos(hour, minute) do
5 * (rem(hour, 12) + minute / 60)
end
def angle(hour, minute, second) do
hour_pos = pos(hour, minute)
angle = abs(6 * (second - hour_pos))
inner_angle = min(angle, 360 - angle)
inner_angle
end
end
IO.puts ClockAngle.angle(2, 20, 20)
Other versions: seisvelas@gist.github/clock
Here's me running a Rosario application that displays the nth fibonacci number:
// fib.rose
// Displays the nth fibonacci number
<- n 8
<- a 0
<- b 1
// asm style loop (label/condition/goto)
label @begin
<- tmp a
<- a b
+= b tmp
+= n -1
!= n 0
goto @begin
// n is 8, so this will display 21
hi a
Compiler Source: seisvelas@github/rosario
This was my first, small project with Language Oriented Programming but I'd like to create something less trivial. Racket is so powerful for language creation, it feels wrong NOT to, even just for fun.
The sum of the terminal leaves is the nth Fibonacci number.
n = | |
f(n) = | ... |
#include <stdio.h>
#include <stdlib.h>
struct fib_node {
int n;
struct fib_node *left, *right;
};
struct fib_node* fib(int n) {
struct fib_node *node;
node = malloc(sizeof(struct fib_node));
node->n = n;
if (n && (n - 1)) {
node->left = fib(n-1);
node->right = fib(n-2);
}
return node;
}
int count_leaves(struct fib_node *node) {
if (node->left && node->right) {
return count_leaves(node->left) +
count_leaves(node->right);
}
return node->n;
}
void main(void) {
// displays 13, the 7th fib number
printf("%d\n", count_leaves(fib(7)));
}
Other approaches: seisvelas@gist.github/fib