I have a 2D array of units students are studying. For each unit there are different numbers of functions (aka objectives) they are studying and for each function, different numbers of prompts they could be asked in an assessment. My data is a 2D array thus:
functions = [
["Unit 1",
[ // function 1
"prompt 1",
"prompt 2",
...,
"prompt n"],
[ // function 2
etc...
My code creates assessments based on which units have been studied by pulling random prompts and then shuffling these into the array (sm1).
Some of these prompts have image files associated with them and all have audio files. The file names for these media files are based on where they occur in our material, e.g. u1f1p1.mp3
So my solution was to match this regularity by creating file names based on their position in the array. Here's my code to do that:
for (var a = 0; a < sm1.length; a++) {// for each of sm1's prompts
for (var b = 0; b <= functions.length-6; b++) { // limit it to units 1-3 of 8 for this specific assessment
for(var c = 1; c < functions[b].length; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
for (var d = 0; d < functions[b][c].length; d++) { // for each prompt for each function for each unit
if(functions[b][c][d] === sm1[a]) { // see if it matches
fileNames.push('u'+(b+1)+'f'+c+'p'+(d+1)); // create file name from index and add to fileNames[]
}
}
}
}
}
This code works fine and, because speed is effectively irrelevant for our purposes, I could say job done. However, I know that this has to be hopelessly inefficient because not only is this a long loop, but it continues to run even after a match is found.
So, two questions:
- What would be the most efficient way of finding a match?
- How can I break once
sm1[n]
is found and go on to look forsm1[n+1]
?