Skip to content

Instantly share code, notes, and snippets.

@HerringtonDarkholme
Last active July 10, 2024 07:31
Show Gist options
  • Save HerringtonDarkholme/3474f0c0a0ae6b78d0767b83ed4f3b83 to your computer and use it in GitHub Desktop.
Save HerringtonDarkholme/3474f0c0a0ae6b78d0767b83ed4f3b83 to your computer and use it in GitHub Desktop.
Cyan's secrete
function findCombinations(numbers, targetSum) {
const result = [];
function find(currentSum, index, currentCombination) {
if (currentSum === targetSum) {
result.push([...currentCombination]);
return;
}
if (currentSum > targetSum || index === numbers.length) return;
// Include the number at the current index.
currentCombination.push(numbers[index]);
find(currentSum + numbers[index], index + 1, currentCombination);
// Exclude the number at the current index.
currentCombination.pop();
find(currentSum, index + 1, currentCombination);
}
find(0, 0, []);
return result;
}
const numbers = [10, 6, 2, 6, 1, 9, 6, 3, 9, 2, 7, 7, 12, 11];
const combinations = findCombinations(numbers, 63);
console.log(combinations);
@Lucifier129
Copy link

Show the probability of each event.

function findCombinations(numbers, targetSum) {
    const result = [];
    function find(currentSum, index, currentCombination) {
        if (currentSum === targetSum) {
            result.push([...currentCombination]);
            return;
        }
        if (currentSum > targetSum || index === numbers.length) return;

        // Include the number at the current index.
        currentCombination.push(index);
        find(currentSum + numbers[index], index + 1, currentCombination);
        
        // Exclude the number at the current index.
        currentCombination.pop();
        find(currentSum, index + 1, currentCombination);
    }

    find(0, 0, []);
    return result;
}


function calculateDistribution(numbersList) {
    const distribution = {};
    const totalNumbers = numbersList.length;

    for (const numbers of numbersList) {
        for (const number of numbers) {
            if (!distribution[number]) {
                distribution[number] = 1;
            } else {
                distribution[number]++;
            }
        }
    }

    for (const number in distribution) {
        distribution[number] /= totalNumbers;
    }

    return distribution;
}



function showDistribution(distribution) {
    for (const number in distribution) {
        console.log(`Number ${number}: ${distribution[number] * 100}%`);
    }
}

const numbers = [10, 6, 2, 6, 1, 9, 6, 3, 9, 2, 7, 7, 12, 11];
const combinations = findCombinations(numbers, 63);
console.log(combinations);
console.log(showDistribution(calculateDistribution(combinations)));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment