Skip to content

Commit 9a44820

Browse files
committed
chore: merge js branch into main with no fast-forward
2 parents 011299a + 4352f44 commit 9a44820

File tree

31 files changed

+2199
-2
lines changed

31 files changed

+2199
-2
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Travelling Salesman Problem - Bitmasking Approach
2+
3+
## English
4+
5+
The Travelling Salesman Problem (TSP) is a classic algorithmic problem in the field of computer science and operations research. It focuses on optimization. In this problem, a salesman is given a list of cities and must determine the shortest possible route that visits each city exactly once and returns to the origin city.
6+
7+
This challenge requires implementing the TSP using bitmasking and dynamic programming to efficiently explore all possible routes without redundant calculations. The solution is implemented in JavaScript using Object-Oriented Programming (OOP) principles and follows DRY (Don't Repeat Yourself) best practices.
8+
9+
### Relevant Code Snippet
10+
11+
```javascript
12+
class TravellingSalesman {
13+
constructor(distanceMatrix) {
14+
this.distanceMatrix = distanceMatrix;
15+
this.n = distanceMatrix.length;
16+
this.memo = Array.from({ length: this.n }, () => []);
17+
}
18+
19+
tsp(mask = 1, pos = 0) {
20+
if (mask === (1 << this.n) - 1) {
21+
return this.distanceMatrix[pos][0];
22+
}
23+
if (this.memo[pos][mask] !== undefined) {
24+
return this.memo[pos][mask];
25+
}
26+
27+
let minCost = Infinity;
28+
for (let city = 0; city < this.n; city++) {
29+
if ((mask & (1 << city)) === 0) {
30+
const newCost = this.distanceMatrix[pos][city] + this.tsp(mask | (1 << city), city);
31+
if (newCost < minCost) {
32+
minCost = newCost;
33+
}
34+
}
35+
}
36+
this.memo[pos][mask] = minCost;
37+
return minCost;
38+
}
39+
}
40+
```
41+
42+
---
43+
44+
## Español
45+
46+
El Problema del Viajante de Comercio (TSP) es un problema clásico en el campo de la informática y la investigación operativa. Se centra en la optimización. En este problema, un viajante debe determinar la ruta más corta posible que visite cada ciudad exactamente una vez y regrese a la ciudad de origen.
47+
48+
Este reto requiere implementar el TSP usando bitmasking y programación dinámica para explorar eficientemente todas las rutas posibles sin cálculos redundantes. La solución está implementada en JavaScript usando principios de Programación Orientada a Objetos (POO) y siguiendo las mejores prácticas de DRY (No te repitas).
49+
50+
### Fragmento de Código Relevante
51+
52+
```javascript
53+
class TravellingSalesman {
54+
constructor(distanceMatrix) {
55+
this.distanceMatrix = distanceMatrix;
56+
this.n = distanceMatrix.length;
57+
this.memo = Array.from({ length: this.n }, () => []);
58+
}
59+
60+
tsp(mask = 1, pos = 0) {
61+
if (mask === (1 << this.n) - 1) {
62+
return this.distanceMatrix[pos][0];
63+
}
64+
if (this.memo[pos][mask] !== undefined) {
65+
return this.memo[pos][mask];
66+
}
67+
68+
let minCost = Infinity;
69+
for (let city = 0; city < this.n; city++) {
70+
if ((mask & (1 << city)) === 0) {
71+
const newCost = this.distanceMatrix[pos][city] + this.tsp(mask | (1 << city), city);
72+
if (newCost < minCost) {
73+
minCost = newCost;
74+
}
75+
}
76+
}
77+
this.memo[pos][mask] = minCost;
78+
return minCost;
79+
}
80+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// TravellingSalesman.js - TSP solver using Bitmasking and Dynamic Programming with OOP and DRY principles
2+
3+
class TravellingSalesman {
4+
constructor(distanceMatrix) {
5+
this.distanceMatrix = distanceMatrix;
6+
this.n = distanceMatrix.length;
7+
this.memo = Array.from({ length: this.n }, () => []);
8+
}
9+
10+
tsp(mask = 1, pos = 0) {
11+
if (mask === (1 << this.n) - 1) {
12+
return this.distanceMatrix[pos][0];
13+
}
14+
if (this.memo[pos][mask] !== undefined) {
15+
return this.memo[pos][mask];
16+
}
17+
18+
let minCost = Infinity;
19+
for (let city = 0; city < this.n; city++) {
20+
if ((mask & (1 << city)) === 0) {
21+
const newCost =
22+
this.distanceMatrix[pos][city] + this.tsp(mask | (1 << city), city);
23+
if (newCost < minCost) {
24+
minCost = newCost;
25+
}
26+
}
27+
}
28+
this.memo[pos][mask] = minCost;
29+
return minCost;
30+
}
31+
}
32+
33+
export default TravellingSalesman;
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/*
2+
Challenge:
3+
Given a set of cities and the distances between every pair of cities, find the shortest possible route that visits each city exactly once and returns to the origin city.
4+
This challenge requires implementing the Travelling Salesman Problem (TSP) using bitmasking and dynamic programming to optimize the solution.
5+
*/
6+
7+
import TravellingSalesman from "./TravellingSalesman.js";
8+
9+
function main() {
10+
const distanceMatrix = [
11+
[0, 10, 15, 20],
12+
[10, 0, 35, 25],
13+
[15, 35, 0, 30],
14+
[20, 25, 30, 0],
15+
];
16+
17+
const tspSolver = new TravellingSalesman(distanceMatrix);
18+
const minCost = tspSolver.tsp();
19+
console.log("Minimum cost to visit all cities:", minCost);
20+
}
21+
22+
main();
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Word Break
2+
3+
## English
4+
5+
The word break problem is a classic example of recursion with memoization, commonly used in natural language processing and text segmentation tasks. It efficiently explores multiple segmentation paths while avoiding redundant computations.
6+
7+
This challenge involves returning all possible valid sentences that can be formed from a string using words from a dictionary.
8+
9+
### Relevant Code Snippet
10+
11+
```javascript
12+
class WordBreak {
13+
constructor(s, wordDict) {
14+
this.s = s;
15+
this.wordDict = new Set(wordDict);
16+
this.memo = new Map();
17+
}
18+
19+
wordBreak(start = 0) {
20+
if (start === this.s.length) {
21+
return [""];
22+
}
23+
24+
if (this.memo.has(start)) {
25+
return this.memo.get(start);
26+
}
27+
28+
const sentences = [];
29+
for (let end = start + 1; end <= this.s.length; end++) {
30+
const word = this.s.substring(start, end);
31+
if (this.wordDict.has(word)) {
32+
const subsentences = this.wordBreak(end);
33+
for (const subsentence of subsentences) {
34+
const sentence = word + (subsentence ? " " + subsentence : "");
35+
sentences.push(sentence);
36+
}
37+
}
38+
}
39+
40+
this.memo.set(start, sentences);
41+
return sentences;
42+
}
43+
}
44+
```
45+
46+
### History
47+
48+
The word break problem has been widely studied in computer science and is commonly used in natural language processing and text segmentation.
49+
50+
---
51+
52+
## Español
53+
54+
Segmentación de Palabras
55+
56+
El problema de segmentación de palabras es un ejemplo clásico de recursión con memoización, comúnmente usado en procesamiento de lenguaje natural y tareas de segmentación de texto. Explora eficientemente múltiples caminos de segmentación evitando cálculos redundantes.
57+
58+
Este reto consiste en devolver todas las posibles oraciones válidas que se pueden formar a partir de una cadena usando palabras de un diccionario.
59+
60+
### Fragmento de Código Relevante
61+
62+
```javascript
63+
class WordBreak {
64+
constructor(s, wordDict) {
65+
this.s = s;
66+
this.wordDict = new Set(wordDict);
67+
this.memo = new Map();
68+
}
69+
70+
wordBreak(start = 0) {
71+
if (start === this.s.length) {
72+
return [""];
73+
}
74+
75+
if (this.memo.has(start)) {
76+
return this.memo.get(start);
77+
}
78+
79+
const sentences = [];
80+
for (let end = start + 1; end <= this.s.length; end++) {
81+
const word = this.s.substring(start, end);
82+
if (this.wordDict.has(word)) {
83+
const subsentences = this.wordBreak(end);
84+
for (const subsentence of subsentences) {
85+
const sentence = word + (subsentence ? " " + subsentence : "");
86+
sentences.push(sentence);
87+
}
88+
}
89+
}
90+
91+
this.memo.set(start, sentences);
92+
return sentences;
93+
}
94+
}
95+
```
96+
97+
### Historia
98+
99+
El problema de segmentación de palabras ha sido ampliamente estudiado en ciencias de la computación y es comúnmente usado en procesamiento de lenguaje natural y segmentación de texto.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// WordBreak.js - Word Break problem using recursion with memoization in JavaScript
2+
3+
class WordBreak {
4+
constructor(s, wordDict) {
5+
this.s = s;
6+
this.wordDict = new Set(wordDict);
7+
this.memo = new Map();
8+
}
9+
10+
wordBreak(start = 0) {
11+
if (start === this.s.length) {
12+
return [""];
13+
}
14+
15+
if (this.memo.has(start)) {
16+
return this.memo.get(start);
17+
}
18+
19+
const sentences = [];
20+
for (let end = start + 1; end <= this.s.length; end++) {
21+
const word = this.s.substring(start, end);
22+
if (this.wordDict.has(word)) {
23+
const subsentences = this.wordBreak(end);
24+
for (const subsentence of subsentences) {
25+
const sentence = word + (subsentence ? " " + subsentence : "");
26+
sentences.push(sentence);
27+
}
28+
}
29+
}
30+
31+
this.memo.set(start, sentences);
32+
return sentences;
33+
}
34+
}
35+
36+
export default WordBreak;
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
Challenge:
3+
Given a string and a dictionary, return all possible valid sentences that can be formed using recursion with memoization.
4+
5+
This solution follows DRY principles and is implemented in JavaScript.
6+
*/
7+
8+
import WordBreak from "./WordBreak.js";
9+
10+
function main() {
11+
const s = "catsanddog";
12+
const wordDict = ["cat", "cats", "and", "sand", "dog"];
13+
14+
const wordBreak = new WordBreak(s, wordDict);
15+
const sentences = wordBreak.wordBreak();
16+
17+
console.log("Possible sentences:");
18+
sentences.forEach((sentence) => console.log(sentence));
19+
}
20+
21+
main();

0 commit comments

Comments
 (0)