Last active
August 29, 2015 13:56
-
-
Save trinary/9294388 to your computer and use it in GitHub Desktop.
Collatz (3n + 1) Conjecture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
text { | |
font: 14px sans-serif; | |
} | |
body { | |
font: sans-serif; | |
} | |
</style> | |
<svg></svg> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
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 = 60; | |
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)}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment