Skip to content

Instantly share code, notes, and snippets.

@johnwalley
Last active October 30, 2018 09:48
Show Gist options
  • Save johnwalley/25b77d49bbbee7aef480d7598708e039 to your computer and use it in GitHub Desktop.
Save johnwalley/25b77d49bbbee7aef480d7598708e039 to your computer and use it in GitHub Desktop.
Recaman Sequence
license: mit
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="960" height="500"></svg>
<script>
var n = 60;
var curr = 0;
var seq = [curr];
for (var i = 1; i < n; i++) {
var next = curr - i;
if (next < 0 || seq.includes(next)) {
curr = curr + i;
seq.push(curr);
} else {
curr = next;
seq.push(next);
}
}
console.log(seq);
var data = [];
var sign = 1;
for (var i = 0; i < n - 1; i++) {
var center = (seq[i] + seq[i+1]) / 2;
var radius = Math.abs(seq[i] - seq[i+1]) / 2;
var dir = Math.sign(seq[i+1] - seq[i]);
data.push({center: center, radius: radius, sign: sign, dir: dir});
sign = -sign;
}
console.log(data);
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g");
var x = d3.scaleLinear().range([0, width]).domain([0, d3.max(seq)])
var arc = d3.arc()
.innerRadius(function(d) { return x(d.radius)})
.outerRadius(function(d) { return x(d.radius)})
.endAngle(function(d) { return d.dir * d.sign * (Math.PI / 2) + (d.sign - 1) * Math.PI/2})
.startAngle(function(d) { return -d.dir * d.sign * (Math.PI /2) + (d.sign - 1) * Math.PI/2});
var DURATION = 300;
g.selectAll('path')
.data(data)
.enter()
.append('path')
.attr("stroke", "steelblue")
.attr("stroke-width", "2")
.attr("d", arc)
.attr("transform", function(d) { return "translate(" + x(d.center) + ",240)"})
.attr("stroke-dasharray", function(d) { return this.getTotalLength() + ", " + this.getTotalLength(); })
.attr("stroke-dashoffset", function(d) { return this.getTotalLength(); })
.transition()
.delay(function(d, i) { return i * DURATION;})
.duration(DURATION * 2)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment