Supongamos que tenemos esta matriz donde se deben de cumplir las siguientes reglas: Filas 1,2 y 3 tienen que sumar 4, la cuarta fila sumará 5 y la última solo 3. La suma de cada columna por separado a,b,c,d siempre sumarán 5.
a b c d | total --- --- --- --- |------- a1 b1 c1 d1 | 4 a2 b2 c2 d2 | 4 a3 b3 c3 d3 | 4 a4 b4 c4 d4 | 5 a5 b5 c5 d5 | 3 --- --- --- ---|------ 5 5 5 5 | 20
Rellenarla de forma manual no es muy complicado recordandome en cierto modo al sudoku o incluso al problema de las 8 reinas.
Una posible solución.
a b c d | total --- --- --- --- |------- 3 1 0 0 | 4 0 2 0 2 | 4 2 0 0 2 | 4 0 1 3 1 | 5 0 1 2 0 | 3 --- --- --- --- |------ 5 5 5 5 | 20
Mi algoritmo consiste en ir rellenando fila por fila aleatoriamente cumpliendo las condiciones tanto de la fila como de la columna.
El problema viene cuando llego al final que no tiene porque coincidir con una solución (se muestran X en el ejemplo que he puesto).
¿Qué solución puede tener esto? A ser posible sin utilizar recursividad.
document.getElementById("btn").addEventListener("click", ejecutar);
function ejecutar() {
m = {
f1: { a:0, b:0, c:0, d:0 },
f2: { a:0, b:0, c:0, d:0 },
f3: { a:0, b:0, c:0, d:0 },
f4: { a:0, b:0, c:0, d:0 },
f5: { a:0, b:0, c:0, d:0 },
}
// maximos de cada fila y columna
max = { a:5, b:5, c:5, d:5 , f1:4, f2:4, f3:4, f4:5, f5:3 };
m.f1.a = random("f1","a");
m.f1.b = random("f1","b");
m.f1.c = random("f1","c");
m.f1.d = random("f1","d");
m.f2.a = random("f2","a");
m.f2.b = random("f2","b");
m.f2.c = random("f2","c");
m.f2.d = random("f2","d");
m.f3.a = random("f3","a");
m.f3.b = random("f3","b");
m.f3.c = random("f3","c");
m.f3.d = random("f3","d");
m.f4.a = random("f4","a");
m.f4.b = random("f4","b");
m.f4.c = random("f4","c");
m.f4.d = random("f4","d");
m.f5.a = random("f5","a");
m.f5.b = random("f5","b");
m.f5.c = random("f5","c");
m.f5.d = random("f5","d");
var html = '';
for (var i = 1; i < 6; i++) {
var f = m["f"+i];
var ok = (max["f"+i]!=0) ? "<b>X</b>" : "";
html += '<tr><td><b>f'+i+'</b></td><td>'+f.a+'</td><td>'+f.b+'</td><td>'+f.c+'</td><td>'+f.d+'</td> <td>'+ok+'</td></tr>';
}
var a = (max.a!=0) ? "<b>X</b>" : "";
var b = (max.b!=0) ? "<b>X</b>" : "";
var c = (max.c!=0) ? "<b>X</b>" : "";
var d = (max.d!=0) ? "<b>X</b>" : "";
html += '<tr><td></td><td>'+a+'</td><td>'+b+'</td><td>'+c+'</td><td>'+d+'</td></tr>';
var matrix = document.getElementById('matrix').innerHTML = html;
}
function random(fila,col) {
maximo = (max[fila] > max[col]) ? max[col] : max[fila];
// console.log("max = "+ maximo);
if (col == "d") {
var dato = maximo;
} else {
var dato = Math.floor(Math.random() * (maximo + 1));
}
max[fila] = max[fila] - dato;
max[col] = max[col] - dato;
return dato;
}
<button id="btn">ejecutar</button>
<table id="matris" class="blueTable">
<thead>
<tr>
<th></th>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
</tr>
</thead>
<tbody id="matrix">
</tbody>
</table>