Randomly separate space into sections

Viewed 38

this seems like it should be simple, but it's not working out for me at the moment.

I'm trying to create horizontal sections, each of which would then be filled in with textured strokes of a certain (or random) color between that particular section's beginning and end, with the next section beginning immediately at the previous section's end. Here's what I have in code:

note that the w(val) is just percentage of width

function vertBG() {
  let sectionsWidths = [0]
  for (let i = 0; i < 10; i++) {
    let sectionWidth = random(w(.13),w(.3))
    sectionsWidths.push(sectionWidth)
  }
  let sections = []
  for (let i = 0; i < 10; i++) {
    let begin = sectionsWidths[i];
    let end = sectionsWidths[i] + sectionsWidths[i+1]
    sections.push([begin,end])
  }
  console.log(sectionsWidths)
  console.log(sections)
  for (let i = 0; i < sections.length; i++) {
    for (let x = sections[i][0]; x < sections[i][1]; x += w(.01)) {
      let r = random(155,255)
      let g = random(155,255)
      let b = random(155,255)
      texStr(x, 0, x, height, w(.2), r, g, b, 50)
    }
  }
}

EDIT adding p5 editor link here https://editor.p5js.org/anton.ermkv/sketches/Dk0sHI771

It works for the first two sections, but not past that as I get the following from logging the sections array:

0: (2) [0, 187.61733953724615]
1: (2) [187.61733953724615, 325.3773163144011]
2: (2) [137.75997677715495, 286.15264510712586]
3: (2) [148.39266832997092, 297.9690613041166]
4: (2) [149.5763929741457, 302.7814557082951]
5: (2) [153.2050627341494, 346.3200062647462]

On line 2, instead of getting the sum of 187... and 137... I just have 137... again and so on down line.

Expected output is to have vertical stripes of varying width going across the canvas. So the array should look something like:

0: (2) [0, 130]
1: (2) [130, 290]
2: (2) [290, 445]
3: (2) [445, 600]

Thanks to anyone having a look at this!

1 Answers

Replace this line:

let end = sectionsWidths[i] + sectionsWidths[i+1]

With this one:

let end = sectionsWidths[i+1]

Basically, you just need to jump to the next index via i+1 and get the value, instead of adding the previous and the next value.

That is, if I correctly understand the expected outcome which is not included in the answer.


Update: after your clarification, I think this code is what you're looking for:

  for (let i = 0; i < 10; i++) {
    const begin = sections[i-1] ? sections[i-1][1] : sectionsWidths[i];
    const end = begin + sectionsWidths[i+1]; // Or sectionsWidths[i]?
    sections.push([begin,end])
  }
Related