Вот версия, адаптированная из приведенной выше пары ответов, которая производит результаты в порядке, указанном в OP, и возвращает строки вместо массивов:
function *cartesianProduct(...arrays) {
if (!arrays.length) yield [];
else {
const [tail, ...head] = arrays.reverse();
const beginning = cartesianProduct(...head.reverse());
for (let b of beginning) for (let t of tail) yield b + t;
}
}
const first = ['a', 'b', 'c', 'd'];
const second = ['e'];
const third = ['f', 'g', 'h', 'i', 'j'];
console.log([...cartesianProduct(first, second, third)])
Что-то вроде этого может работать:
local function notes2nums(input)
local map = {A = 9, ["A#"] = 10, B = 11, C = 0, ["C#"] = 1, D = 2, ["D#"] = 3, E = 4, F = 5, ["F#"] = 6, G = 7, ["G#"] = 8}
local base, prev
return (input:gsub("([^,]+)", function(note)
local num = map[note] or error(("Unexpected note value '%s'"):format(note))
base = base or num
num = num - base
if prev and num < prev then num = num + 12 end
prev = num
return tostring(num)
end))
end
print(notes2nums("D,F#,A"))
print(notes2nums("C,E,G,A#,D,F,A"))
print(notes2nums("G#,B,D#,F#,B"))
Это печатает:
0,4,7
0,4,7,10,14,17,21
0,3,7,10,15
map
. Добавьтеprint(note)
после строки 4, чтобы увидеть значение в переменнойnote
, которую он пытается найти. – Paul Kulchenko 13 July 2018 в 21:09