Skip to content

Instantly share code, notes, and snippets.

@curran
Last active September 10, 2016 19:59
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 curran/e199be2e4e6d16d8e34ed2d3cff76e9c to your computer and use it in GitHub Desktop.
Save curran/e199be2e4e6d16d8e34ed2d3cff76e9c to your computer and use it in GitHub Desktop.
Cantor Set
license: mit
border: no
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style> body { margin: 0 } </style>
</head>
<body>
<svg width="960" height="500"></svg>
<script>
var rules = {
A: "ABA",
B: "BBB"
},
initialState = "A",
iterations = 8,
L = function(str){
return str.split("").map(function (d){
return rules[d];
}).join("")
},
data = d3.range(iterations).map(function iterate(i){
return i ? L(iterate(i - 1)) : initialState;
});
console.log(JSON.stringify(data, null, 2));
// Prints the following:
// [
// "A",
// "ABA",
// "ABABBBABA",
// "ABABBBABABBBBBBBBBABABBBABA",
// "ABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABA",
// "ABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABA",
// ...
var svg = d3.select("svg"),
x = d3.scaleBand()
.range([0, svg.attr("width")]),
y = d3.scaleBand()
.domain(d3.range(iterations))
.rangeRound([0, svg.attr("height")]),
rects = data
.map(function(str, j){
x.domain(d3.range(str.length));
return str.split("")
.map(function (symbol, i){
return {
symbol: symbol,
x: x(i),
y: y(j),
width: x.bandwidth(),
height: y.bandwidth()
};
})
.filter(function (d){
return d.symbol === "A";
});
})
.reduce(function (a, b){
return a.concat(b);
}, []);
svg.selectAll("rect").data(rects)
.enter().append("rect")
.attr("x", function(d){ return d.x; })
.attr("y", function(d){ return d.y; })
.attr("width", function(d){ return d.width; })
.attr("height", function(d){ return d.height; })
.attr("fill", "black");
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment