I am struggling with a simple fill of 2D array, following a pattern given by MIDI notes list Midi Notes Array. Basically, what I need to do is to fill a full width and hight of a canvas with numbers from 0 - 127.
I know that the logic is flawed, but I can't figure out how to solve it.
let m = 0
let n = 0;
let blockW = Math.floor(width/12)
let blockH = Math.floor(height/10)
for (var i = 0; i < 12; i++) {
for (var j = 0; j < 10; j++) {
for (var x = blockW * m; x < blockW *(m+1); x++) {
midiArray[x] = []
for (var y = blockW * m; y < blockW *(m+1); y++) {
midiArray[x][y] = n
}
}
}
m++
n++
}
Any help would be appreciated !
I don't think you're approaching the problem in an optimal way, but here's the minimal changes to make your code coherent:
let midiArray = [];
function setup() {
createCanvas(400, 400);
noLoop();
// There is no need for the extra variable m
let n = 0;
let blockW = Math.floor(width / 12);
let blockH = Math.floor(height / 10);
// j - rows (iterate over rows first so that n increases from left to right)
for (var j = 0; j < 10; j++) {
// i - columns
for (var i = 0; i < 12; i++) {
// When finding pixel positions for the current block use i and j which
// indicate the column and row.
for (var x = blockW * i; x < blockW * (i + 1); x++) {
if (!midiArray[x]) {
// When we're generating the pixels for the second row we will be
// re-using the existing array at midiArray[x], so only initialize
// this the first time we are populating pixels for each particular x
midiArray[x] = [];
}
for (var y = blockH * j; y < blockH * (j + 1); y++) {
midiArray[x][y] = n;
}
}
// Increase n for each block (not just for each row)
n++;
}
}
}
function draw() {
background('red');
loadPixels();
for (let x = 0; x < midiArray.length; x++) {
if (midiArray[x]) {
for (let y = 0; y < midiArray[x].length; y++) {
set(x, y, color(map(midiArray[x][y], 0, 120, 0, 255)));
}
}
}
updatePixels();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>