Generating the vertices and edges of an n-cube in javascript

Written by Ben Wendt

An n-cube is a geometric shape analogous to a cube, but in an arbitrary number of dimensions.

The algorithm I’ve laid out does a recursive routine for finding the vertices and then looks for all edges within one unit of each to define the edges.

The function becomes non-response with values over 14. This is because the number of points in an n-cube is given by 2n and the number of edges is n2n-1. So the expected memory usage of this function is O(2n), which is going to blow up with any fairly large value.

var nCube = function(n) {

    if (n == 1) {
      return {
        "points" :[[0], [1]],
        "edges" : [[0, 1]]
      };
    } else {
      var L, i, j, prev = nCube(n - 1), out = {
        "dimensions" : n,
        "points" : [],
        "edges" : []
      };

      for (i = 0; i < prev.points.length; i++) {
        for (j = 0; j < 2; j++) {
          (function() {
            var fit = prev.points[i].slice();
            fit.push(j);
            out.points.push(fit);

          })();
        }
      }
      // surely there is a faster recursive method of defining edges, but...
      for (i = 0; i < out.points.length; i++) {
        for (j = i; j < out.points.length; j++) {
          if (i == j) continue;
          if (distance(out.points[i], out.points[j]) == 1) {
            out.edges.push([i,j]);
          }
        }
      }

      return out;
    }
  };