Skip to content

Instantly share code, notes, and snippets.

@trinary
Created November 30, 2013 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinary/7725461 to your computer and use it in GitHub Desktop.
Save trinary/7725461 to your computer and use it in GitHub Desktop.
Collatz conjectures
{"description":"Collatz conjectures","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"pingpong","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"thumbnail":"http://i.imgur.com/XrKoKGV.gif"}
function collatz(n) {
var ret = { count: 0, max: n};
if (n === undefined || n === 0) {return ret; }
while (n != 1) {
ret.count = ret.count + 1;
if (n % 2 === 0) { n = n / 2;}
else { n = ((3*n)+1)/2; }
if (n > ret.max) { ret.max = n}
}
return ret;
}
var data = d3.range(5200).map(function(d) { return collatz(d)});
// mess with width to see different patterns.
var width = 80;
var countColor = d3.scale.linear()
.domain(d3.extent(data, function(d) { return d.count;}))
.range(["#CFE2D8","#1F201F"])
.interpolate(d3.interpolateHsl);
var maxColor = d3.scale.linear()
.domain(d3.extent(data, function(d) { return d.max;}))
.range(["#DBD6E9","#11111B"])
.interpolate(d3.interpolateHsl);
var c = d3.select("svg").append("g");
c.attr("transform", "translate(20,42)");
c.append("text").classed("label",true).attr("transform","translate(0, -11)").text("Mouse over a box.");
c.selectAll("rect").data(data)
.enter()
.append("rect")
.attr("x", function(d,i) { return (i % width) * 16})
.attr("y", function(d,i) { return (Math.floor(i / width) * 16 )})
.attr("width", 10)
.attr("height",10)
.attr("fill", function(d) { return countColor(d.count) })
.attr("stroke", function(d) { return maxColor(d.max) })
.attr("stroke-width", "2px")
.on("mouseover", function(d,i) { d3.select(".label").text(i + " took " + d.count + " cycles and reached a max of " + d.max)});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment