function CartesianProduct() {
const [result, setResult] = useState({});
const A = ["a", "b", "c", "D"];
const B = [1, 2, 3];
function getProduct(a, b) {
const results = [];
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
let temp = Array.isArray(a[i]) ? [...a[i]] : [a[i]];
results.push([...temp, b[j]]);
}
}
return results;
}
function getProductMultiple(sets) {
let temp = sets[0];
const N = sets.length;
for (let i = 1; i < N; i++) {
temp = getProduct(temp, sets[i]);
}
return temp;
}
function Result({ sets }) {
const products = getProductMultiple(sets);
return (
<pre>
<ol>
{sets.map((s, i) => (
<li key={i}>{JSON.stringify(s)}</li>
))}
</ol>
size: {products.length}
<br />
{JSON.stringify(products)}
</pre>
);
}
return (
<div>
<h3>A x B</h3>
<Result sets={[A, B]} />
-----
<h3>A x A</h3>
<Result sets={[A, A]} />
-----
<h3>bit strings</h3>
<Result
sets={[
["0", "1"],
["0", "1"],
]}
/>
<h3>bit strings of length 3</h3>
<Result
sets={[
["0", "1"],
["0", "1"],
["0", "1"],
]}
/>
<h3>Random</h3>
<Result
sets={[
[1, 2, 3, 4],
[5, 6, 7, 8],
]}
/>
</div>
);
}