javascript coding test course, salesman’s dilemma

Published on:

Author: Coding Expert

Problem Description

A salesman is visiting various cities to sell products. The salesman knows the prices of products that can be sold in each city, as well as the travel costs between cities. The salesman needs to set a goal and find the most efficient route to achieve that goal. In other words, the salesman must visit each city only once and find a route that allows him to return home while maximizing his profit.

Input

The input consists of the number of cities n, an array of sale prices prices, and a 2D array of travel costs costs. The prices are represented by prices[i] for the price of the product in the i-th city, and the travel costs are represented by costs[i][j] for the cost of traveling from city i to city j.

Output

The function should return the maximum profit that the salesman can achieve by returning home slowly.

Constraints

  • 2 ≤ n ≤ 10
  • 0 ≤ prices[i] ≤ 1000
  • 0 ≤ costs[i][j] ≤ 1000

Problem-Solving Approach

This problem is similar to the ‘Traveling Salesman Problem’ and can be solved using backtracking or dynamic programming. Essentially, the salesman needs to try all possible combinations to optimize the route that visits all cities and returns home.

Step 1: Understanding the Problem

Since the salesman must visit all cities, he needs to explore all paths between cities while considering the item sale profits and travel costs for each path. The goal is to calculate profits and costs to select the optimal route.

Step 2: Designing the Algorithm

To solve this problem, follow these steps:

  • Assume each city as the starting city and visit each city while exploring all possible paths.
  • Calculate the sale profits and travel costs for each path to update the optimal profit.
  • After visiting all cities, calculate the cost to return to the original city as well.

Step 3: Implementation

Now let’s move on to the implementation phase. We will write a function in JavaScript to find the maximum profit of the salesman.


function maxProfit(n, prices, costs) {
    let maxProfit = -Infinity;

    function backtrack(currentCity, visited, currentProfit) {
        // If all cities are visited, return home.
        if (visited.length === n) {
            const returnCost = costs[currentCity][0]; // Cost to return to the starting city
            const totalProfit = currentProfit - returnCost; // Calculate total profit
            maxProfit = Math.max(maxProfit, totalProfit);
            return;
        }

        // Visit each city.
        for (let nextCity = 0; nextCity < n; nextCity++) {
            if (!visited.includes(nextCity)) {
                visited.push(nextCity); // Record city visit
                const nextProfit = currentProfit + prices[nextCity]; // Calculate profit for next city
                const travelCost = costs[currentCity][nextCity]; // Travel cost
                backtrack(nextCity, visited, nextProfit - travelCost); // Recursive call
                visited.pop(); // Remove visit record (backtracking)
            }
        }
    }

    // Start from the 0th city
    backtrack(0, [0], prices[0]);

    return maxProfit;
}

// Example usage
const n = 4;
const prices = [100, 70, 90, 40];
const costs = [
    [0, 10, 15, 20],
    [10, 0, 35, 25],
    [15, 35, 0, 30],
    [20, 25, 30, 0]
];

console.log(maxProfit(n, prices, costs));
        

Step 4: Code Explanation

The maxProfit function defined above performs the following tasks:

  • currentCity: Tracks the current city.
  • visited: Tracks the cities visited so far.
  • currentProfit: Tracks the cumulative profit so far.

We recursively explore each city. After visiting all cities, we calculate the cost to return home to update the total profit.

Example Test

When running the code, the maxProfit function will return the maximum profit. It is advisable to experiment with various input values to observe the performance of the algorithm.

Conclusion

In this lesson, we explored the Traveling Salesman Problem. It is important to understand the theoretical background and implementation methods that frequently appear in coding tests. By exploring various routes and quantitatively calculating the optimal profit, we learned how to utilize the powerful features of JavaScript.

In the next session, we will cover another algorithm problem. If you have any questions or feedback, please leave a comment!