"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Approaching Brute Force Algorithm Using Javascript

Approaching Brute Force Algorithm Using Javascript

Published on 2024-08-16
Browse:592

Approaching Brute Force Algorithm Using Javascript

  1. Below are few examples which is started with simple to advance level (Travelling Salesman Problem and 0/1 knapsack problem)
  2. These examples are based on brute force Algorithm

My Note:-

  1. There are several downsides of this Brute Force Algorithm but before directly jumping into Dynamic programming and other approaches
  2. you should have ideas on this approach and you must find out why we need a Dynamic Programming pattern (Recursion Memorization)

If you closely observe the pattern for the brute force

const wrapper = (value) => {
    const helper = (combinedArray, depth) => {
       if (depth == 3) {
          // operation
           return ;
       }

       for (let coin of coins) {
           if (value - coin >=0) {
               combinedArray.push(coin);
               helper(combinedArray, label 1);
               combinedArray.pop();
           }
       }
    }

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

const res = wrapper(value);
console.log(res);

Q1. Start with 2 coin combinations

const wrapper = () => {
    const coinSide = ['head', 'tail']
    const result = [];
    const helper = (currentCombination, depth) => {
        if (depth == 2) {
            result.push([...currentCombination]);
            return ;
        }

        for (side of coinSide) {
            currentCombination.push(side);
            helper(currentCombination, depth  1);
            currentCombination.pop()
        }
    }

    helper([], 0);

    return result;
};

const res = wrapper();

console.log(res);

Q2. Start with 3 coin combinations

const wrapper = () => {
    const coinSide = ['head', 'tail']
    const result = [];
    const helper = (currentCombination, depth) => {
        if (depth == 3) {
            result.push([...currentCombination]);
            return ;
        }

        for (side of coinSide) {
            currentCombination.push(side);
            helper(currentCombination, depth  1);
            currentCombination.pop()
        }
    }

    helper([], 0);

    return result;
};

const res = wrapper();

console.log(res);

/*
[
  [ 'head', 'head', 'head' ],
  [ 'head', 'head', 'tail' ],
  [ 'head', 'tail', 'head' ],
  [ 'head', 'tail', 'tail' ],
  [ 'tail', 'head', 'head' ],
  [ 'tail', 'head', 'tail' ],
  [ 'tail', 'tail', 'head' ],
  [ 'tail', 'tail', 'tail' ]
]
*/
,

, , ,
,

,
const wrapper = () => {
    const result = [];
    const group = ['b1', 'b2', 'g1']
    const helper = (combination, depth) => {
        if (depth == 3) {
            result.push([...combination]);
            return;
        }

        for (let item of group) {
            if (combination.indexOf(item) 
]
*/

Q3. Seating arrangement

// Minimum coin Problem
const wrapper = (value) => {
    let result = 99999;
    let resultArr = [];
    const coins = [10, 6, 1];
    const helper = (value, label, combinedArray) => {
       if (value == 0) {
           if (result > label) {
               result = label;
               resultArr = [...combinedArray]
           }
           return ;
       }

       for (let coin of coins) {
           if (value - coin >=0) {
               combinedArray.push(coin);
               helper(value-coin, label 1, combinedArray);
               combinedArray.pop();
           }
       }
    }

    helper(value, 0, []);
    console.log(resultArr)

    return result;
};

const res = wrapper(12);

console.log(res);
/*
[ 6, 6 ]
2
*/
const wrapper = () => { const result = []; const group = ['b1', 'b2', 'g1'] const helper = (combination, depth) => { if (depth == 3) { result.push([...combination]); return; } for (let item of group) { if (combination.indexOf(item) , , ,
, ,
// Problem 1: Generating All Subsets of a Set
// Problem Statement:
// Given a set of unique elements, generate all possible subsets (the power set).
// This solution need more enhancement.
// Example:
// Input: [1, 2, 3]
// Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]


const wrapper = () => {
    const result = [[]];
    const input = [1,2,3];
    input.forEach(item => result.push([item]));

    const helper = (combination, depth) => {
        if (depth == 2) {
            if (result.indexOf(combination) 



Q4. Coin / Sum problem

// Travelling sales man problem using brut force algorithm

function calculateDistance(matrix, path) {
  let totalDistance = 0;
  for (let i = 0; i  {
      if (depth == 4) {
          result.push([...combination]);

          return;
      }

      for (let item of arr) {
          if (combination.indexOf(item)  index)
  console.log(cities)
  const permutations = permute(cities);
  console.log(permutations)
  let minDistance = Infinity;
  let bestPath = [];

  for (let path of permutations) {
    const distance = calculateDistance(matrix, path);
    if (distance 



Q5.Set generation

// 0/1 knapsack Brut force Problem
function knapsackBruteForce(weights, values, capacity) {
  let n = weights.length;
  let maxValue = 0;
  const subsetResult = [];
  const binaryVals = [0, 1];

  // Function to calculate the total weight and value of a subset
  function calculateSubset(subset) {
    let totalWeight = 0;
    let totalValue = 0;
    for (let i = 0; i  {
      if (depth == 4) {
          subsetResult.push([...combination]);
          return ;
      }

      for (let item of binaryVals) {
          combination.push(item);
          helper(combination, depth  1);
          combination.pop()
      }

  }

    helper([], 0);
    console.log(subsetResult)
  // Generate all subsets using binary representation
  for (let subset of subsetResult) {
    let { totalWeight, totalValue } = calculateSubset(subset);
    if (totalWeight  maxValue) {
      maxValue = totalValue;
    }
  }

  return maxValue;
}

// Example usage:
const weights = [2, 3, 4, 5];
const values = [3, 4, 5, 6];
const capacity = 5;
const maxVal = knapsackBruteForce(weights, values, capacity);

console.log(`The maximum value in the knapsack is: ${maxVal}`);
/*
[
  [ 0, 0, 0, 0 ], [ 0, 0, 0, 1 ],
  [ 0, 0, 1, 0 ], [ 0, 0, 1, 1 ],
  [ 0, 1, 0, 0 ], [ 0, 1, 0, 1 ],
  [ 0, 1, 1, 0 ], [ 0, 1, 1, 1 ],
  [ 1, 0, 0, 0 ], [ 1, 0, 0, 1 ],
  [ 1, 0, 1, 0 ], [ 1, 0, 1, 1 ],
  [ 1, 1, 0, 0 ], [ 1, 1, 0, 1 ],
  [ 1, 1, 1, 0 ], [ 1, 1, 1, 1 ]
]
The maximum value in the knapsack is: 7
*/

Q6.Travelling sales man problem using brut force algorithm

Approaching Brute Force Algorithm Using Javascript

    // Travelling sales man problem using brut force algorithm function calculateDistance(matrix, path) { let totalDistance = 0; for (let i = 0; i { if (depth == 4) { result.push([...combination]); return; } for (let item of arr) { if (combination.indexOf(item) index) console.log(cities) const permutations = permute(cities); console.log(permutations) let minDistance = Infinity; let bestPath = []; for (let path of permutations) { const distance = calculateDistance(matrix, path); if (distance
  1. Q7. 0/1 knapsack Brut force Problem
// 0/1 knapsack Brut force Problem function knapsackBruteForce(weights, values, capacity) { let n = weights.length; let maxValue = 0; const subsetResult = []; const binaryVals = [0, 1]; // Function to calculate the total weight and value of a subset function calculateSubset(subset) { let totalWeight = 0; let totalValue = 0; for (let i = 0; i { if (depth == 4) { subsetResult.push([...combination]); return ; } for (let item of binaryVals) { combination.push(item); helper(combination, depth 1); combination.pop() } } helper([], 0); console.log(subsetResult) // Generate all subsets using binary representation for (let subset of subsetResult) { let { totalWeight, totalValue } = calculateSubset(subset); if (totalWeight maxValue) { maxValue = totalValue; } } return maxValue; } // Example usage: const weights = [2, 3, 4, 5]; const values = [3, 4, 5, 6]; const capacity = 5; const maxVal = knapsackBruteForce(weights, values, capacity); console.log(`The maximum value in the knapsack is: ${maxVal}`); /* [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 1 ], [ 0, 0, 1, 0 ], [ 0, 0, 1, 1 ], [ 0, 1, 0, 0 ], [ 0, 1, 0, 1 ], [ 0, 1, 1, 0 ], [ 0, 1, 1, 1 ], [ 1, 0, 0, 0 ], [ 1, 0, 0, 1 ], [ 1, 0, 1, 0 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 0 ], [ 1, 1, 0, 1 ], [ 1, 1, 1, 0 ], [ 1, 1, 1, 1 ] ] The maximum value in the knapsack is: 7 */

Release Statement This article is reproduced at: https://dev.to/ashutoshsarangi/approaching-brute-force-algorithm-using-javascript-4ppl?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3