Skip to content

Commit 6988818

Browse files
committed
better algorithm for covering all state transitions
1 parent 509ed7e commit 6988818

File tree

2 files changed

+37
-8
lines changed

2 files changed

+37
-8
lines changed

test/jasmine/assets/transitions.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'use strict';
2+
3+
/**
4+
* Given n states (denoted by their indices 0..n-1) this routine produces
5+
* a sequence of indices such that you efficiently execute each transition
6+
* from any state to any other state.
7+
*/
8+
module.exports = function transitions(n) {
9+
var out = [0];
10+
var nextStates = [];
11+
var i;
12+
for(i = 0; i < n; i++) nextStates[i] = (i + 1) % n;
13+
var finishedStates = 0;
14+
var thisState = 0;
15+
var nextState;
16+
while(finishedStates < n) {
17+
nextState = nextStates[thisState];
18+
if(nextState === thisState) {
19+
// I don't actually know how to prove that this algorithm works,
20+
// but I've never seen it fail for n>1
21+
// For prime n it's the same sequence as the one I started with
22+
// (n transitions of +1 index, then n transitions +2 etc...)
23+
// but this one works for non-prime n as well.
24+
throw new Error('your transitions algo failed.');
25+
}
26+
nextStates[thisState] = (nextStates[thisState] + 1) % n;
27+
if(nextStates[thisState] === thisState) finishedStates++;
28+
out.push(nextState);
29+
thisState = nextState;
30+
}
31+
if(out.length !== n * (n - 1) + 1) {
32+
throw new Error('your transitions algo failed.');
33+
}
34+
return out;
35+
};

test/jasmine/tests/scatter_test.js

+2-8
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ var createGraphDiv = require('../assets/create_graph_div');
99
var destroyGraphDiv = require('../assets/destroy_graph_div');
1010
var customAssertions = require('../assets/custom_assertions');
1111
var failTest = require('../assets/fail_test');
12+
var transitions = require('../assets/transitions');
1213

1314
var assertClip = customAssertions.assertClip;
1415
var assertNodeDisplay = customAssertions.assertNodeDisplay;
@@ -655,14 +656,7 @@ describe('end-to-end scatter tests', function() {
655656

656657
// visit each case N times, in an order that covers each *transition*
657658
// from any case to any other case.
658-
var indices = [];
659-
var curIndex = 0;
660-
for(i = 1; i < cases.length; i++) {
661-
for(j = 0; j < cases.length; j++) {
662-
indices.push(curIndex);
663-
curIndex = (curIndex + i) % cases.length;
664-
}
665-
}
659+
var indices = transitions(cases.length);
666660

667661
var p = Plotly.plot(gd, [
668662
{y: [1, 2], text: 'a'},

0 commit comments

Comments
 (0)