Skip to content

Instantly share code, notes, and snippets.

@dduugg
Created December 29, 2014 02:30
Show Gist options
  • Save dduugg/f94e923854514ae7fd1f to your computer and use it in GitHub Desktop.
Save dduugg/f94e923854514ae7fd1f to your computer and use it in GitHub Desktop.
N-Queens solutions in MCPL and JavaScript

Solutions to the N-Queens Problem

MCPL implementation, published by Martin Richards:

GET "mcpl.h"

STATIC count, all

FUN try
: ?, =all, ? => count++

: ld, cols, rd => LET poss = ~(ld | cols | rd) & all
                  WHILE poss DO
                  { LET bit = poss & -poss
                    poss -:= bit
                    try( (ld|bit)<<1, cols|bit, (rd|bit)>>1 )
                  }

FUN start : =>
  all := 1
  FOR n = 1 TO 12 DO
  { count := 0
    try(0, 0, 0)
    writef("There are %5d solutions to %2d-queens problem\n",
                      count,             n )
    all := 2*all + 1
  }
  RETURN 0

JavaScript translation (maximizing code similarity, at the expense of code quality):

var count, all

function _try(ld, cols, rd) {
  if (cols == all) count++

  var poss = ~(ld | cols | rd) & all
  while (poss)
  { var bit = poss & -poss
    poss -= bit
    _try( (ld|bit)<<1, cols|bit, (rd|bit)>>1 )
  }
}

(function start() {
  all = 1
  for (n = 1; n <= 12; n++)
  { count = 0
    _try(0, 0, 0)
    console.log("There are " + count + " solutions to " +
                n + "-queens problem")
    all = 2*all + 1
  }
  return 0
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment