У вас есть 2 проблемы для решения здесь:
1) Получите все возможные типы счетов для N клиентов. Вы можете сделать это следующим образом:
const allAccounts = [];
for (let i = 1; i <= customersNumber; i++) {
allAccounts.push(`C${i}-Sole`);
for (let j = 1; j <= customersNumber; j++) {
if (i === j) continue;
allAccounts.push(`C${i}-Primary C${j}-NonPrimary`);
}
}
Для 2 клиентов результат будет:
[
"C1-Sole",
"C1-Primary C2-NonPrimary",
"C2-Sole",
"C2-Primary C1-NonPrimary"
]
2) Получить все возможные комбинации длины r (с повторениями) из этого массива. Здесь мы хотим исключить два типа комбинаций:
- , которые имеют 2 или более индивидуальных аккаунта для одного и того же клиента.
- те, кто не подключен (не имеют общих клиентов, если я вас правильно понял)
// checks if two accounts are connected
function connected(customers1, customers2) {
return customers1.filter(cu => customers2.includes(cu)).length > 0;
}
// checks if acc1 and acc2 are the same Sole account
function sameSoleAccount(acc1, acc2) {
return acc1.type === 'Sole' && acc1 === acc2;
}
function printAccount(i, a) {
const c = a.customers;
return a.type === 'Sole' ? `${c[0]}-A${i}-Sole` : `${c[0]}-A${i}-Primary ${c[1]}-A${i}-NonPrimary`;
}
function combination(chosen, arr, index, r) {
if (index === r) {
const combination = chosen.map((c, i) => printAccount(i + 1, arr[c])).join(', ');
console.log(combination);
return;
}
for (let i = 0; i < arr.length; i++) {
if (chosen.length === 0 ||
chosen.some(ch => !sameSoleAccount(arr[ch], arr[i])
&& connected(arr[ch].customers, arr[i].customers))) {
const copy = chosen.slice();
copy[index] = i;
combination(copy, arr, index + 1, r);
}
}
}
function allPossibleCombinations(accountsNumber, customersNumber) {
const allAccounts = [];
for (let i = 1; i <= customersNumber; i++) {
allAccounts.push({customers: [`C${i}`], type: 'Sole'});
for (let j = 1; j <= customersNumber; j++) {
if (i === j) continue;
allAccounts.push({customers: [`C${i}`, `C${j}`], type: 'Joint'});
}
}
console.log(`All possible combinations for ${customersNumber} customers and ${accountsNumber} accounts: `);
combination([], allAccounts, 0, accountsNumber, 0, allAccounts.length - 1);
}
allPossibleCombinations(2, 2);