Chris
Chris

Reputation: 336

Recursively adding mid-points between points in an array

I am trying to create a function which takes all points in an array and returns an array with an additional point between each pair of adjacent points. For instance, starting with (2, 10), I would get the following iterations to the list:

(2, 14)
(2, 8, 14)
(2, 5, 8, 11, 14)
(2, 3.5, 5, 6.5, 8, 9.5, 11, 12.5, 14)

My code:

var Width = 1000
var Height = 1000
const svg = document.getElementById('svg1')
svg.setAttribute('width', Width)
svg.setAttribute('height', Height)

var seg = function(point) {
  var segment = document.createElementNS("http://www.w3.org/2000/svg", "circle")
  segment.setAttribute("cx", point.x)
  segment.setAttribute("cy", point.y)
  segment.setAttribute("r", 1)
  segment.setAttribute("fill", "none")
  segment.setAttribute('stroke', "#f00")
  segment.setAttribute('stroke-width', 0.5)
  svg.appendChild(segment)
}

const mid = function(pa, pb) {
  let cx = (pa.x + pb.x) / 2
  let cy = (pa.y + pb.y) / 2
  return {
    x: cx,
    y: cy
  }
}

var testarray = [{
  x: 0,
  y: 100
}, {
  x: 400,
  y: 50
}]

const split = function(a) {

  let b = []
  let c = []
  for (i = 0; i < a.length - 1; i++) {
    b.push(mid(a[i], a[i + 1]))
    c.push(a[i])
    c.push(b[i])
  }
  c.push(a[a.length - 1])
  return c

}

while (testarray.length < 30) {
  var testarray = split(testarray)
}

var counter = 0
while (counter < testarray.length) {
  seg(testarray[counter])
  counter++
}
<svg id="svg1"></svg>

Fixed code, thanks!

Upvotes: 0

Views: 93

Answers (2)

gandaliter
gandaliter

Reputation: 10101

The problem is that the array is changing shape as you add items to it, but your loop on i doesn't take account of that. A quick solution would be to increment i after splicing in the new value, as well as as usual in the for loop.

 const split = function(a){
    for(i=0;i<a.length-1;i++){
        let b = mid(a[i],a[i+1])
        a.splice(i+1,0,b)
        i++
        if(a.length>100){return}
    }
 }

Upvotes: 0

Prune
Prune

Reputation: 77847

The problem is that you're modifying the list while you iterate through it. Stop that! :-)

Create a second list that you build from the original, and return the second list. Alternately, you could try iterating in reverse order, but this leaves you dependent on the splice semantics -- which is still a dangerous practice.

Upvotes: 2

Related Questions