foresight
v0.0.1
Published
Predict the next output of a process which can only output binary states.
Downloads
4
Maintainers
Readme
foresight
Predict the next output of a process which can only output binary states.
If a process outputs only two states (random or predictable), it's sometimes useful to predict the next state the process would output.
Why?
Here is a usage application:
function isAwesome(input) {
if (expensiveComputation(input))
return true;
if (expensiveOperation(input))
return true;
return false;
}
// can potentially reduce potential computations by predicting which algorithm would hit first
function betterIsAwesome(input) {
var order = foresight.guess();
var algorithms = [expensiveComputation, expensiveOperation];
var n = 2;
if (order === 'algo1') {
while(n-- > 0) {
if(algorithms[1-n](input)) {
(n == 1) && foresight.move('algo1') || foresight.move('algo2');
return true;
}
}
} else {
while(n-- > 0) {
if(algorithms[n](input)) {
(n == 1) && foresight.move('algo2') || foresight.move('algo1');
return true;
}
}
}
return false;
}
Usage
$ npm install --save foresight
var foresightMaker = require('foresight');
var foresight = foresightMaker();
foresight.move('head');
var guess = foresight.guess();
API
foresightMaker(options)
A factory function that returns an instance of foresight
object.
options
Type: object
options.moves
By default foresight
uses coin-flipping semantics to capture actual moves and to predict the next move.
You may remap these values to something else. Once they're remapped, you must use the new values for foresight.move(actual)
. And as well as expect them as output of foresight.guess()
.
Example:
options.move = {
head: 'left',
tail: 'right'
}
Default:
options.move = {
head: 'head',
tail: 'tail',
pass: 'pass'
}
foresight.move(actual)
Input the actual state output of the tracking process.
actual
Value: head
, tail
, or values mapped to head
and tail
.
NOTE: actual
may not equal to pass
(in default move semantics) or move mapped to pass
. Only foresight
may return pass
; which indicates that it is uncertain of its guess.
foresight.guess()
Returns a guess of the next state that a process would output.
If foresight
is uncertain of the next move, it would output pass
(or remapped value of pass
).
Otherwise, if foresight
is certain of the next move, it would output head
or tail
(or remapped values).
Credit
Code is ported to a usable npm module from: http://www.loper-os.org/bad-at-entropy/manmach.html
I did not come up with the underlying algorithm. I just rewrapped it into nicer API.
Weaknesses
As demonstrated by someone, the algorithm is deterministic, and one can beat it. You should expect that the process you're tracking won't likely output the precise sequences of moves that foresight
would guess incorrectly most of the time.
The algorithm is light enough to be used in favour of a PRNG
in some applications. Especially when heavyweight prediction tools isn't a likely solution.
License
MIT