Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0023190f5a | |||
| 2552ea9423 | |||
| e08be0574d | |||
| 3797e7715f | |||
| 19c4516d22 | |||
| 06c345e8f0 | |||
| d9ae630fe5 | |||
| 132c4ebced |
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "vue-nonograms-solid",
|
||||
"version": "1.6.3",
|
||||
"version": "1.8.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "vue-nonograms-solid",
|
||||
"version": "1.6.3",
|
||||
"version": "1.8.1",
|
||||
"dependencies": {
|
||||
"fireworks-js": "^2.10.8",
|
||||
"flag-icons": "^7.5.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vue-nonograms-solid",
|
||||
"version": "1.6.3",
|
||||
"version": "1.8.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
75
scripts/simulate_difficulty.js
Normal file
75
scripts/simulate_difficulty.js
Normal file
@@ -0,0 +1,75 @@
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { generateRandomGrid, calculateHints } from '../src/utils/puzzleUtils.js';
|
||||
import { solvePuzzle } from '../src/utils/solver.js';
|
||||
|
||||
const OUTPUT_FILE = 'difficulty_simulation_results.json';
|
||||
const CSV_FILE = 'difficulty_simulation_results.csv';
|
||||
|
||||
// Configuration
|
||||
const SIZES = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80]; // Steps of 5 up to 50, then 10
|
||||
const DENSITIES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9];
|
||||
const SAMPLES_PER_POINT = 20; // Adjust based on time/accuracy needs
|
||||
|
||||
console.log('Starting Monte Carlo Simulation for Nonogram Difficulty...');
|
||||
console.log(`Config: Sizes=${SIZES.length}, Densities=${DENSITIES.length}, Samples=${SAMPLES_PER_POINT}`);
|
||||
|
||||
const results = [];
|
||||
const csvRows = ['size,density,avg_solved_percent,min_solved_percent,max_solved_percent,avg_time_ms'];
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
for (const size of SIZES) {
|
||||
for (const density of DENSITIES) {
|
||||
let totalSolved = 0;
|
||||
let minSolved = 100;
|
||||
let maxSolved = 0;
|
||||
let totalTime = 0;
|
||||
|
||||
process.stdout.write(`Simulating Size: ${size}x${size}, Density: ${density} ... `);
|
||||
|
||||
for (let i = 0; i < SAMPLES_PER_POINT; i++) {
|
||||
const t0 = performance.now();
|
||||
|
||||
// 1. Generate
|
||||
const grid = generateRandomGrid(size, density);
|
||||
const { rowHints, colHints } = calculateHints(grid);
|
||||
|
||||
// 2. Solve
|
||||
const { percentSolved } = solvePuzzle(rowHints, colHints);
|
||||
|
||||
const t1 = performance.now();
|
||||
|
||||
totalSolved += percentSolved;
|
||||
minSolved = Math.min(minSolved, percentSolved);
|
||||
maxSolved = Math.max(maxSolved, percentSolved);
|
||||
totalTime += (t1 - t0);
|
||||
}
|
||||
|
||||
const avgSolved = totalSolved / SAMPLES_PER_POINT;
|
||||
const avgTime = totalTime / SAMPLES_PER_POINT;
|
||||
|
||||
results.push({
|
||||
size,
|
||||
density,
|
||||
avgSolved,
|
||||
minSolved,
|
||||
maxSolved,
|
||||
avgTime
|
||||
});
|
||||
|
||||
csvRows.push(`${size},${density},${avgSolved.toFixed(2)},${minSolved.toFixed(2)},${maxSolved.toFixed(2)},${avgTime.toFixed(2)}`);
|
||||
|
||||
console.log(`Avg Solved: ${avgSolved.toFixed(1)}%`);
|
||||
}
|
||||
}
|
||||
|
||||
const totalDuration = (Date.now() - startTime) / 1000;
|
||||
console.log(`Simulation complete in ${totalDuration.toFixed(1)}s`);
|
||||
|
||||
// Save results
|
||||
fs.writeFileSync(OUTPUT_FILE, JSON.stringify(results, null, 2));
|
||||
fs.writeFileSync(CSV_FILE, csvRows.join('\n'));
|
||||
|
||||
console.log(`Results saved to ${OUTPUT_FILE} and ${CSV_FILE}`);
|
||||
@@ -8,6 +8,7 @@ import StatusPanel from './components/StatusPanel.vue';
|
||||
import GuidePanel from './components/GuidePanel.vue';
|
||||
import WinModal from './components/WinModal.vue';
|
||||
import CustomGameModal from './components/CustomGameModal.vue';
|
||||
import SimulationView from './components/SimulationView.vue';
|
||||
import FixedBar from './components/FixedBar.vue';
|
||||
import ReloadPrompt from './components/ReloadPrompt.vue';
|
||||
|
||||
@@ -15,6 +16,7 @@ import ReloadPrompt from './components/ReloadPrompt.vue';
|
||||
const store = usePuzzleStore();
|
||||
const { t, locale, setLocale, locales } = useI18n();
|
||||
const showCustomModal = ref(false);
|
||||
const showSimulation = ref(false);
|
||||
const showGuide = ref(false);
|
||||
const deferredPrompt = ref(null);
|
||||
const canInstall = ref(false);
|
||||
@@ -173,7 +175,8 @@ onUnmounted(() => {
|
||||
<!-- Modals Teleport -->
|
||||
<Teleport to="body">
|
||||
<WinModal v-if="store.isGameWon" />
|
||||
<CustomGameModal v-if="showCustomModal" @close="showCustomModal = false" />
|
||||
<CustomGameModal v-if="showCustomModal" @close="showCustomModal = false" @open-simulation="showSimulation = true" />
|
||||
<SimulationView v-if="showSimulation" @close="showSimulation = false" />
|
||||
<ReloadPrompt />
|
||||
</Teleport>
|
||||
</main>
|
||||
|
||||
@@ -1,16 +1,174 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
|
||||
import { usePuzzleStore } from '@/stores/puzzle';
|
||||
import { useI18n } from '@/composables/useI18n';
|
||||
import { calculateDifficulty } from '@/utils/puzzleUtils';
|
||||
import { HelpCircle } from 'lucide-vue-next';
|
||||
|
||||
const emit = defineEmits(['close']);
|
||||
const emit = defineEmits(['close', 'open-simulation']);
|
||||
const store = usePuzzleStore();
|
||||
const { t } = useI18n();
|
||||
|
||||
const customSize = ref(10);
|
||||
const fillRate = ref(50);
|
||||
const errorMsg = ref('');
|
||||
const difficultyCanvas = ref(null);
|
||||
const isDragging = ref(false);
|
||||
|
||||
const drawMap = () => {
|
||||
const canvas = difficultyCanvas.value;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
|
||||
// Clear
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
// Draw Gradient Background
|
||||
// Optimization: Create an image data once if static, but here it's small enough.
|
||||
const imgData = ctx.createImageData(width, height);
|
||||
const data = imgData.data;
|
||||
|
||||
// Ranges:
|
||||
// X: Fill Rate 10% -> 90%
|
||||
// Y: Size 5 -> 80
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
// Map x, y to fillRate, size
|
||||
// y=0 -> size 80 (top), y=height -> size 5 (bottom)
|
||||
// x=0 -> fill 10%, x=width -> fill 90%
|
||||
|
||||
const normalizedX = x / width;
|
||||
const normalizedY = 1 - (y / height); // 0 at bottom, 1 at top
|
||||
|
||||
const fRate = 0.1 + normalizedX * 0.8; // 0.1 to 0.9
|
||||
const sSize = 5 + normalizedY * 75; // 5 to 80
|
||||
|
||||
const { value } = calculateDifficulty(fRate, sSize);
|
||||
|
||||
// Color Mapping:
|
||||
// Green (0%) -> Yellow (50%) -> Red (100%)
|
||||
// Hue: 120 -> 0
|
||||
const hue = 120 * (1 - value / 100);
|
||||
|
||||
// Convert HSL to RGB (Simplified)
|
||||
// Saturation 100%, Lightness 50%
|
||||
const [r, g, b] = hslToRgb(hue / 360, 1, 0.5);
|
||||
|
||||
const index = (y * width + x) * 4;
|
||||
data[index] = r;
|
||||
data[index + 1] = g;
|
||||
data[index + 2] = b;
|
||||
data[index + 3] = 255; // Alpha
|
||||
}
|
||||
}
|
||||
ctx.putImageData(imgData, 0, 0);
|
||||
|
||||
// Draw current position
|
||||
// Map current fillRate/size to x,y
|
||||
// Fill: 10..90. Size: 5..80.
|
||||
const currentFill = Math.max(10, Math.min(90, fillRate.value));
|
||||
const currentSize = Math.max(5, Math.min(80, customSize.value));
|
||||
|
||||
const posX = ((currentFill - 10) / 80) * width;
|
||||
const posY = (1 - (currentSize - 5) / 75) * height;
|
||||
|
||||
// Draw Crosshair/Circle
|
||||
ctx.beginPath();
|
||||
ctx.arc(posX, posY, 6, 0, Math.PI * 2);
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fill();
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = '#000';
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
const hslToRgb = (h, s, l) => {
|
||||
let r, g, b;
|
||||
if (s === 0) {
|
||||
r = g = b = l; // achromatic
|
||||
} else {
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
r = hue2rgb(p, q, h + 1 / 3);
|
||||
g = hue2rgb(p, q, h);
|
||||
b = hue2rgb(p, q, h - 1 / 3);
|
||||
}
|
||||
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
|
||||
};
|
||||
|
||||
const updateFromEvent = (e) => {
|
||||
const canvas = difficultyCanvas.value;
|
||||
if (!canvas) return;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
|
||||
// Handle Touch or Mouse
|
||||
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
|
||||
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
|
||||
|
||||
let x = clientX - rect.left;
|
||||
let y = clientY - rect.top;
|
||||
|
||||
// Clamp
|
||||
x = Math.max(0, Math.min(rect.width, x));
|
||||
y = Math.max(0, Math.min(rect.height, y));
|
||||
|
||||
// Reverse Map
|
||||
// x / width -> fillRate (10..90)
|
||||
// 1 - y / height -> size (5..80)
|
||||
|
||||
const normalizedX = x / rect.width;
|
||||
const normalizedY = 1 - (y / rect.height);
|
||||
|
||||
const newFill = 10 + normalizedX * 80;
|
||||
const newSize = 5 + normalizedY * 75;
|
||||
|
||||
fillRate.value = Math.round(newFill);
|
||||
customSize.value = Math.round(newSize);
|
||||
};
|
||||
|
||||
const startDrag = (e) => {
|
||||
isDragging.value = true;
|
||||
updateFromEvent(e);
|
||||
// Add global listeners for mouse to handle dragging outside canvas
|
||||
window.addEventListener('mousemove', onDrag);
|
||||
window.addEventListener('mouseup', stopDrag);
|
||||
};
|
||||
|
||||
const onDrag = (e) => {
|
||||
if (!isDragging.value) return;
|
||||
updateFromEvent(e);
|
||||
};
|
||||
|
||||
const stopDrag = () => {
|
||||
isDragging.value = false;
|
||||
window.removeEventListener('mousemove', onDrag);
|
||||
window.removeEventListener('mouseup', stopDrag);
|
||||
};
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('mousemove', onDrag);
|
||||
window.removeEventListener('mouseup', stopDrag);
|
||||
});
|
||||
|
||||
const showAdvanced = ref(false);
|
||||
|
||||
const toggleAdvanced = () => {
|
||||
showAdvanced.value = !showAdvanced.value;
|
||||
if (showAdvanced.value) {
|
||||
nextTick(drawMap);
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
const savedSize = localStorage.getItem('nonograms_custom_size');
|
||||
@@ -22,6 +180,14 @@ onMounted(() => {
|
||||
if (savedFillRate && !isNaN(savedFillRate)) {
|
||||
fillRate.value = Math.max(10, Math.min(90, Number(savedFillRate)));
|
||||
}
|
||||
|
||||
// Don't draw map initially if hidden
|
||||
});
|
||||
|
||||
watch([customSize, fillRate], () => {
|
||||
if (showAdvanced.value) {
|
||||
drawMap();
|
||||
}
|
||||
});
|
||||
|
||||
watch(customSize, (newVal) => {
|
||||
@@ -41,12 +207,12 @@ const handleSnap = () => {
|
||||
customSize.value = snapToStep(Number(customSize.value), 5);
|
||||
};
|
||||
|
||||
const difficultyLevel = computed(() => {
|
||||
return calculateDifficulty(fillRate.value / 100);
|
||||
const difficultyInfo = computed(() => {
|
||||
return calculateDifficulty(fillRate.value / 100, customSize.value);
|
||||
});
|
||||
|
||||
const difficultyColor = computed(() => {
|
||||
switch(difficultyLevel.value) {
|
||||
switch(difficultyInfo.value.level) {
|
||||
case 'extreme': return '#ff3333';
|
||||
case 'hardest': return '#ff9933';
|
||||
case 'harder': return '#ffff33';
|
||||
@@ -71,45 +237,77 @@ const confirm = () => {
|
||||
<div class="modal-overlay" @click.self="emit('close')">
|
||||
<div class="modal glass-panel">
|
||||
<h2>{{ t('custom.title') }}</h2>
|
||||
<p>{{ t('custom.prompt') }}</p>
|
||||
|
||||
<div class="input-group">
|
||||
<div class="range-value">{{ customSize }}</div>
|
||||
<input
|
||||
type="range"
|
||||
v-model="customSize"
|
||||
min="5"
|
||||
max="80"
|
||||
step="1"
|
||||
@change="handleSnap"
|
||||
/>
|
||||
<div class="range-scale">
|
||||
<span>5</span>
|
||||
<span>80</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-content">
|
||||
<div class="sliders-section">
|
||||
<div class="slider-container">
|
||||
<p>{{ t('custom.prompt') }}</p>
|
||||
<div class="input-group">
|
||||
<div class="range-value">{{ customSize }}</div>
|
||||
<input
|
||||
type="range"
|
||||
v-model="customSize"
|
||||
min="5"
|
||||
max="80"
|
||||
step="1"
|
||||
@change="handleSnap"
|
||||
/>
|
||||
<div class="range-scale">
|
||||
<span>5</span>
|
||||
<span>80</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p>{{ t('custom.fillRate') }}</p>
|
||||
<div class="input-group">
|
||||
<div class="range-value">{{ fillRate }}%</div>
|
||||
<input
|
||||
type="range"
|
||||
v-model="fillRate"
|
||||
min="10"
|
||||
max="90"
|
||||
step="5"
|
||||
/>
|
||||
<div class="range-scale">
|
||||
<span>10%</span>
|
||||
<span>90%</span>
|
||||
<div class="slider-container">
|
||||
<p>{{ t('custom.fillRate') }}</p>
|
||||
<div class="input-group">
|
||||
<div class="range-value">{{ fillRate }}%</div>
|
||||
<input
|
||||
type="range"
|
||||
v-model="fillRate"
|
||||
min="10"
|
||||
max="90"
|
||||
step="1"
|
||||
/>
|
||||
<div class="range-scale">
|
||||
<span>10%</span>
|
||||
<span>90%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="map-section" v-if="showAdvanced">
|
||||
<canvas
|
||||
ref="difficultyCanvas"
|
||||
width="400"
|
||||
height="400"
|
||||
@mousedown="startDrag"
|
||||
@touchstart.prevent="startDrag"
|
||||
@touchmove.prevent="onDrag"
|
||||
@touchend="stopDrag"
|
||||
></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="difficulty-indicator">
|
||||
<span class="label">{{ t('custom.difficulty') }}:</span>
|
||||
<span class="value" :style="{ color: difficultyColor }">
|
||||
{{ t(`difficulty.${difficultyLevel}`) }}
|
||||
</span>
|
||||
<div class="label-row">
|
||||
<div class="label">{{ t('custom.difficulty') }}</div>
|
||||
<button class="help-btn" @click="emit('open-simulation')" :title="t('custom.simulationHelp') || 'How is this calculated?'">
|
||||
<HelpCircle class="icon-sm" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="difficulty-row">
|
||||
<div class="level" :style="{ color: difficultyColor }">{{ t(`difficulty.${difficultyInfo.level}`) }}</div>
|
||||
<div class="percentage" :style="{ color: difficultyColor }">({{ difficultyInfo.value }}%)</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="advanced-toggle">
|
||||
<button class="btn-text" @click="toggleAdvanced">
|
||||
{{ showAdvanced ? 'Ukryj mapę trudności' : 'Pokaż mapę trudności' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="errorMsg" class="error">{{ errorMsg }}</p>
|
||||
@@ -141,7 +339,7 @@ const confirm = () => {
|
||||
.modal {
|
||||
padding: 40px;
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
max-width: 800px;
|
||||
width: 90%;
|
||||
border: 1px solid var(--accent-cyan);
|
||||
box-shadow: 0 0 50px rgba(0, 242, 255, 0.2);
|
||||
@@ -149,6 +347,54 @@ const confirm = () => {
|
||||
transition: all 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 40px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.modal-content {
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.sliders-section {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.map-section {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
canvas {
|
||||
width: 400px;
|
||||
height: 400px;
|
||||
border: 2px solid var(--panel-border);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 0 20px rgba(0, 242, 255, 0.1);
|
||||
cursor: crosshair;
|
||||
background: #000;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
canvas {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 2rem;
|
||||
color: var(--accent-cyan);
|
||||
@@ -162,6 +408,11 @@ p {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.slider-container {
|
||||
width: 100%;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.input-group {
|
||||
margin-bottom: 20px;
|
||||
display: flex;
|
||||
@@ -222,14 +473,66 @@ input[type="range"]::-moz-range-thumb {
|
||||
}
|
||||
|
||||
.difficulty-indicator {
|
||||
margin: 20px 0;
|
||||
font-size: 1.2rem;
|
||||
margin: 20px 0 40px 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.label-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.help-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 4px;
|
||||
border-radius: 50%;
|
||||
transition: color 0.3s, background 0.3s;
|
||||
}
|
||||
|
||||
.help-btn:hover {
|
||||
color: var(--accent-cyan);
|
||||
background: rgba(0, 242, 255, 0.1);
|
||||
}
|
||||
|
||||
.icon-sm {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.difficulty-row {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
white-space: nowrap;
|
||||
height: 1.5em; /* Reserve space for one line of text */
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.level {
|
||||
font-size: 1.4rem;
|
||||
font-weight: bold;
|
||||
text-transform: uppercase;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.percentage {
|
||||
font-size: 1rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.difficulty-indicator .label {
|
||||
@@ -251,6 +554,25 @@ input[type="range"]::-moz-range-thumb {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.btn-text {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--accent-cyan);
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
opacity: 0.8;
|
||||
transition: opacity 0.3s;
|
||||
}
|
||||
|
||||
.btn-text:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.advanced-toggle {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
|
||||
310
src/components/SimulationView.vue
Normal file
310
src/components/SimulationView.vue
Normal file
@@ -0,0 +1,310 @@
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import { generateRandomGrid, calculateHints } from '@/utils/puzzleUtils';
|
||||
import { solvePuzzle } from '@/utils/solver';
|
||||
import { X, Play, Square, RotateCcw } from 'lucide-vue-next';
|
||||
|
||||
const emit = defineEmits(['close']);
|
||||
|
||||
const SIZES = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50];
|
||||
const DENSITIES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9];
|
||||
const SAMPLES_PER_POINT = 10; // Reduced for web performance demo
|
||||
|
||||
const isRunning = ref(false);
|
||||
const progress = ref(0);
|
||||
const currentStatus = ref('Ready');
|
||||
const results = ref([]);
|
||||
const simulationSpeed = ref(1); // 1 = Normal, 2 = Fast (less render updates)
|
||||
|
||||
let stopRequested = false;
|
||||
|
||||
const startSimulation = async () => {
|
||||
if (isRunning.value) return;
|
||||
isRunning.value = true;
|
||||
stopRequested = false;
|
||||
results.value = [];
|
||||
progress.value = 0;
|
||||
|
||||
const totalSteps = SIZES.length * DENSITIES.length;
|
||||
let stepCount = 0;
|
||||
|
||||
for (const size of SIZES) {
|
||||
for (const density of DENSITIES) {
|
||||
if (stopRequested) {
|
||||
currentStatus.value = 'Stopped';
|
||||
isRunning.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
currentStatus.value = `Simulating ${size}x${size} @ ${(density * 100).toFixed(0)}%`;
|
||||
|
||||
let totalSolved = 0;
|
||||
|
||||
// Run samples
|
||||
for (let i = 0; i < SAMPLES_PER_POINT; i++) {
|
||||
const grid = generateRandomGrid(size, density);
|
||||
const { rowHints, colHints } = calculateHints(grid);
|
||||
const { percentSolved } = solvePuzzle(rowHints, colHints);
|
||||
totalSolved += percentSolved;
|
||||
|
||||
// Yield to UI every few samples to keep it responsive
|
||||
if (i % 2 === 0) await new Promise(r => setTimeout(r, 0));
|
||||
}
|
||||
|
||||
const avgSolved = totalSolved / SAMPLES_PER_POINT;
|
||||
|
||||
results.value.unshift({
|
||||
size,
|
||||
density,
|
||||
avgSolved: avgSolved.toFixed(1)
|
||||
});
|
||||
|
||||
stepCount++;
|
||||
progress.value = (stepCount / totalSteps) * 100;
|
||||
}
|
||||
}
|
||||
|
||||
isRunning.value = false;
|
||||
currentStatus.value = 'Completed';
|
||||
};
|
||||
|
||||
const stopSimulation = () => {
|
||||
stopRequested = true;
|
||||
};
|
||||
|
||||
const getRowColor = (solved) => {
|
||||
if (solved >= 90) return 'color-easy';
|
||||
if (solved >= 60) return 'color-harder';
|
||||
if (solved >= 30) return 'color-hardest';
|
||||
return 'color-extreme';
|
||||
};
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="modal-overlay" @click.self="emit('close')">
|
||||
<div class="modal glass-panel">
|
||||
<div class="header">
|
||||
<h2>Difficulty Simulation</h2>
|
||||
<button class="close-btn" @click="emit('close')">
|
||||
<X />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<div class="controls">
|
||||
<div class="status-bar">
|
||||
<div class="status-text">{{ currentStatus }}</div>
|
||||
<div class="progress-track">
|
||||
<div class="progress-fill" :style="{ width: progress + '%' }"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button v-if="!isRunning" class="btn-neon" @click="startSimulation">
|
||||
<Play class="icon" /> Start Simulation
|
||||
</button>
|
||||
<button v-else class="btn-neon secondary" @click="stopSimulation">
|
||||
<Square class="icon" /> Stop
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="results-container">
|
||||
<table class="results-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Size</th>
|
||||
<th>Density</th>
|
||||
<th>Solved (Logic)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(row, idx) in results" :key="idx" :class="getRowColor(row.avgSolved)">
|
||||
<td>{{ row.size }}x{{ row.size }}</td>
|
||||
<td>{{ (row.density * 100).toFixed(0) }}%</td>
|
||||
<td>{{ row.avgSolved }}%</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-if="results.length === 0" class="empty-state">
|
||||
Press Start to run Monte Carlo simulation
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: var(--modal-overlay);
|
||||
backdrop-filter: blur(5px);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 3000;
|
||||
animation: fadeIn 0.3s ease;
|
||||
}
|
||||
|
||||
.modal {
|
||||
padding: 30px;
|
||||
width: 90%;
|
||||
max-width: 600px;
|
||||
height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--accent-cyan);
|
||||
box-shadow: 0 0 50px rgba(0, 242, 255, 0.2);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: var(--accent-cyan);
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
padding-bottom: 15px;
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.status-text {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.progress-track {
|
||||
width: 100%;
|
||||
height: 4px;
|
||||
background: var(--panel-bg-strong);
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: var(--accent-cyan);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.btn-neon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.results-container {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.results-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.results-table th {
|
||||
text-align: left;
|
||||
padding: 8px;
|
||||
color: var(--text-muted);
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--panel-bg);
|
||||
}
|
||||
|
||||
.results-table td {
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.color-easy { color: #33ff33; }
|
||||
.color-harder { color: #ffff33; }
|
||||
.color-hardest { color: #ff9933; }
|
||||
.color-extreme { color: #ff3333; }
|
||||
|
||||
.empty-state {
|
||||
padding: 40px;
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Scrollbar styling */
|
||||
.results-container::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.results-container::-webkit-scrollbar-track {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.results-container::-webkit-scrollbar-thumb {
|
||||
background: var(--panel-border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
</style>
|
||||
@@ -231,7 +231,8 @@ const buildShareSVG = () => {
|
||||
|
||||
// Difficulty Logic
|
||||
const densityPercent = Math.round(store.currentDensity * 100);
|
||||
const difficultyKey = calculateDifficulty(store.currentDensity);
|
||||
const diffInfo = calculateDifficulty(store.currentDensity, store.size);
|
||||
const difficultyKey = diffInfo.level;
|
||||
let diffColor = '#33ff33';
|
||||
if (difficultyKey === 'extreme') diffColor = '#ff3333';
|
||||
else if (difficultyKey === 'hardest') diffColor = '#ff9933';
|
||||
|
||||
@@ -52,24 +52,79 @@ export function generateRandomGrid(size, density = 0.5) {
|
||||
return grid;
|
||||
}
|
||||
|
||||
export function calculateDifficulty(density) {
|
||||
// Shannon Entropy: H(x) = -x*log2(x) - (1-x)*log2(1-x)
|
||||
// Normalized to 0-1 range (since max entropy at 0.5 is 1)
|
||||
|
||||
// Avoid log(0)
|
||||
if (density <= 0 || density >= 1) return 'easy';
|
||||
|
||||
const entropy = -density * Math.log2(density) - (1 - density) * Math.log2(1 - density);
|
||||
|
||||
// Thresholds based on entropy
|
||||
// 0.5 density -> entropy 1.0 (Extreme)
|
||||
// 0.4/0.6 density -> entropy ~0.97 (Extreme)
|
||||
// 0.3/0.7 density -> entropy ~0.88 (Hardest)
|
||||
// 0.2/0.8 density -> entropy ~0.72 (Harder)
|
||||
// <0.2/>0.8 density -> entropy <0.72 (Easy)
|
||||
export function calculateDifficulty(density, size = 10) {
|
||||
// Data derived from Monte Carlo Simulation (Logical Solver)
|
||||
// Format: { size: [solved_pct_at_0.1, ..., solved_pct_at_0.9] }
|
||||
// Densities: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9
|
||||
const SIM_DATA = {
|
||||
5: [89, 74, 74, 81, 97, 98, 99, 100, 100],
|
||||
10: [57, 20, 16, 54, 92, 100, 100, 100, 100],
|
||||
15: [37, 10, 2, 12, 68, 100, 100, 100, 100],
|
||||
20: [23, 3, 1, 2, 37, 100, 100, 100, 100],
|
||||
25: [16, 0, 0, 1, 19, 99, 100, 100, 100],
|
||||
30: [8, 0, 0, 0, 5, 99, 100, 100, 100],
|
||||
35: [6, 0, 0, 0, 4, 91, 100, 100, 100],
|
||||
40: [3, 0, 0, 0, 2, 91, 100, 100, 100],
|
||||
45: [2, 0, 0, 0, 1, 82, 100, 100, 100],
|
||||
50: [2, 0, 0, 0, 1, 73, 100, 100, 100],
|
||||
60: [0, 0, 0, 0, 0, 35, 100, 100, 100],
|
||||
70: [0, 0, 0, 0, 0, 16, 100, 100, 100],
|
||||
80: [0, 0, 0, 0, 0, 1, 100, 100, 100]
|
||||
};
|
||||
|
||||
if (entropy >= 0.96) return 'extreme'; // approx 38% - 62%
|
||||
if (entropy >= 0.85) return 'hardest'; // approx 28% - 38% & 62% - 72%
|
||||
if (entropy >= 0.65) return 'harder'; // approx 17% - 28% & 72% - 83%
|
||||
return 'easy';
|
||||
// Helper to get interpolated value from array
|
||||
const getSimulatedSolvedPct = (s, d) => {
|
||||
// Find closest sizes
|
||||
const sizes = Object.keys(SIM_DATA).map(Number).sort((a, b) => a - b);
|
||||
let sLower = sizes[0];
|
||||
let sUpper = sizes[sizes.length - 1];
|
||||
|
||||
for (let i = 0; i < sizes.length - 1; i++) {
|
||||
if (s >= sizes[i] && s <= sizes[i+1]) {
|
||||
sLower = sizes[i];
|
||||
sUpper = sizes[i+1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Clamp density to 0.1 - 0.9
|
||||
const dClamped = Math.max(0.1, Math.min(0.9, d));
|
||||
// Index in array: 0.1 -> 0, 0.9 -> 8
|
||||
const dIndex = (dClamped - 0.1) * 10;
|
||||
const dLowerIdx = Math.floor(dIndex);
|
||||
const dUpperIdx = Math.ceil(dIndex);
|
||||
const dFraction = dIndex - dLowerIdx;
|
||||
|
||||
// Bilinear Interpolation
|
||||
|
||||
// 1. Interpolate Density for Lower Size
|
||||
const rowLower = SIM_DATA[sLower];
|
||||
const valLower = rowLower[dLowerIdx] * (1 - dFraction) + (rowLower[dUpperIdx] || rowLower[dLowerIdx]) * dFraction;
|
||||
|
||||
// 2. Interpolate Density for Upper Size
|
||||
const rowUpper = SIM_DATA[sUpper];
|
||||
const valUpper = rowUpper[dLowerIdx] * (1 - dFraction) + (rowUpper[dUpperIdx] || rowUpper[dLowerIdx]) * dFraction;
|
||||
|
||||
// 3. Interpolate Size
|
||||
if (sLower === sUpper) return valLower;
|
||||
const sFraction = (s - sLower) / (sUpper - sLower);
|
||||
|
||||
return valLower * (1 - sFraction) + valUpper * sFraction;
|
||||
};
|
||||
|
||||
const solvedPct = getSimulatedSolvedPct(size, density);
|
||||
|
||||
// Difficulty Score: Inverse of Solved Percent
|
||||
// 100% Solved -> 0 Difficulty
|
||||
// 0% Solved -> 100 Difficulty
|
||||
const value = Math.round(100 - solvedPct);
|
||||
|
||||
// Thresholds
|
||||
let level = 'easy';
|
||||
if (value >= 90) level = 'extreme'; // < 10% Solved
|
||||
else if (value >= 60) level = 'hardest'; // < 40% Solved
|
||||
else if (value >= 30) level = 'harder'; // < 70% Solved
|
||||
else level = 'easy'; // > 70% Solved
|
||||
|
||||
return { level, value };
|
||||
}
|
||||
|
||||
278
src/utils/solver.js
Normal file
278
src/utils/solver.js
Normal file
@@ -0,0 +1,278 @@
|
||||
|
||||
/**
|
||||
* Represents the state of a cell in the solver.
|
||||
* -1: Unknown
|
||||
* 0: Empty
|
||||
* 1: Filled
|
||||
*/
|
||||
|
||||
/**
|
||||
* Solves a single line (row or column) based on hints and current knowledge.
|
||||
* Uses the "Left-Right Overlap" algorithm to find common filled cells.
|
||||
* Also identifies definitely empty cells (reachable by no block).
|
||||
*
|
||||
* @param {number[]} currentLine - Array of -1, 0, 1
|
||||
* @param {number[]} hints - Array of block lengths
|
||||
* @returns {number[]} - Updated line (or null if contradiction/impossible - though shouldn't happen for valid puzzles)
|
||||
*/
|
||||
function solveLine(currentLine, hints) {
|
||||
const length = currentLine.length;
|
||||
|
||||
// If no hints, all must be empty
|
||||
if (hints.length === 0 || (hints.length === 1 && hints[0] === 0)) {
|
||||
return Array(length).fill(0);
|
||||
}
|
||||
|
||||
// Helper to check if a block can be placed at start index
|
||||
const canPlace = (line, start, blockSize) => {
|
||||
if (start + blockSize > line.length) return false;
|
||||
// Check if any cell in block is 0 (Empty) -> Invalid
|
||||
for (let i = start; i < start + blockSize; i++) {
|
||||
if (line[i] === 0) return false;
|
||||
}
|
||||
// Check boundaries (must be separated by empty or edge)
|
||||
if (start > 0 && line[start - 1] === 1) return false;
|
||||
if (start + blockSize < line.length && line[start + blockSize] === 1) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// 1. Calculate Left-Most Positions
|
||||
const leftPositions = [];
|
||||
let currentIdx = 0;
|
||||
for (let hIndex = 0; hIndex < hints.length; hIndex++) {
|
||||
const block = hints[hIndex];
|
||||
// Find first valid position
|
||||
while (currentIdx <= length - block) {
|
||||
if (canPlace(currentLine, currentIdx, block)) {
|
||||
// Verify we can fit remaining blocks
|
||||
// Simple heuristic: do we have enough space?
|
||||
// A full recursive check is better but slower.
|
||||
// For "Logical Solver" we assume valid placement is possible if we respect current constraints.
|
||||
// However, strictly, we need to know if there is *any* valid arrangement starting here.
|
||||
// Let's use a recursive check with memoization for "can fit rest".
|
||||
if (canFitRest(currentLine, currentIdx + block + 1, hints, hIndex + 1)) {
|
||||
leftPositions.push(currentIdx);
|
||||
currentIdx += block + 1; // Move past this block + 1 space
|
||||
break;
|
||||
}
|
||||
}
|
||||
currentIdx++;
|
||||
}
|
||||
if (leftPositions.length <= hIndex) return null; // Impossible
|
||||
}
|
||||
|
||||
// 2. Calculate Right-Most Positions (by reversing line and hints)
|
||||
// This is symmetrical to Left-Most.
|
||||
// Instead of implementing reverse logic, we can just reverse inputs, run left-most, and reverse back.
|
||||
// But we need to respect the "currentLine" constraints which might be asymmetric.
|
||||
|
||||
// Actually, "Right-Most" is just "Left-Most" on the reversed grid.
|
||||
const reversedLine = [...currentLine].reverse();
|
||||
const reversedHints = [...hints].reverse();
|
||||
const rightPositionsReversed = [];
|
||||
|
||||
currentIdx = 0;
|
||||
for (let hIndex = 0; hIndex < reversedHints.length; hIndex++) {
|
||||
const block = reversedHints[hIndex];
|
||||
while (currentIdx <= length - block) {
|
||||
if (canPlace(reversedLine, currentIdx, block)) {
|
||||
if (canFitRest(reversedLine, currentIdx + block + 1, reversedHints, hIndex + 1)) {
|
||||
rightPositionsReversed.push(currentIdx);
|
||||
currentIdx += block + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
currentIdx++;
|
||||
}
|
||||
if (rightPositionsReversed.length <= hIndex) return null;
|
||||
}
|
||||
|
||||
// Convert reversed positions to actual indices
|
||||
// index in reversed = length - 1 - (original_index + block_size - 1)
|
||||
// original_start = length - 1 - (reversed_start + block_size - 1) = length - reversed_start - block_size
|
||||
const rightPositions = rightPositionsReversed.map((rStart, i) => {
|
||||
const block = reversedHints[i];
|
||||
return length - rStart - block;
|
||||
}).reverse();
|
||||
|
||||
|
||||
// 3. Intersect
|
||||
const newLine = [...currentLine];
|
||||
|
||||
// Fill intersection
|
||||
for (let i = 0; i < hints.length; i++) {
|
||||
const l = leftPositions[i];
|
||||
const r = rightPositions[i];
|
||||
const block = hints[i];
|
||||
|
||||
// If overlap exists: [r, l + block - 1]
|
||||
// Example: Block 5. Left: 2, Right: 4.
|
||||
// Left: ..XXXXX...
|
||||
// Right: ....XXXXX.
|
||||
// Overlap: ..XXX...
|
||||
// Indices: max(l, r) to min(l+block, r+block) - 1 ?
|
||||
// Range is [r, l + block - 1] (inclusive)
|
||||
|
||||
if (r < l + block) {
|
||||
for (let k = r; k < l + block; k++) {
|
||||
newLine[k] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine Empty cells?
|
||||
// A cell is empty if it is not covered by ANY block in ANY valid configuration.
|
||||
// This is harder with just L/R limits.
|
||||
// However, we can use the "Simple Glue" logic:
|
||||
// If a cell is outside the range [LeftLimit[i], RightLimit[i] + block] for ALL i, it's empty.
|
||||
// Wait, indices are not strictly partitioned. Block 1 could be at 0 or 10.
|
||||
// But logic dictates order.
|
||||
// Range of block i is [LeftPositions[i], RightPositions[i] + hints[i]].
|
||||
// If a cell k is not in ANY of these ranges, it is 0.
|
||||
|
||||
// Mask of possible filled cells
|
||||
const possibleFilled = Array(length).fill(false);
|
||||
for (let i = 0; i < hints.length; i++) {
|
||||
for (let k = leftPositions[i]; k < rightPositions[i] + hints[i]; k++) {
|
||||
possibleFilled[k] = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (let k = 0; k < length; k++) {
|
||||
if (!possibleFilled[k]) {
|
||||
newLine[k] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return newLine;
|
||||
}
|
||||
|
||||
// Memoized helper for checking if hints fit
|
||||
const memo = new Map();
|
||||
function canFitRest(line, startIndex, hints, hintIndex) {
|
||||
// Optimization: If hints are empty, we just need to check if remaining line has no '1's
|
||||
if (hintIndex >= hints.length) {
|
||||
for (let i = startIndex; i < line.length; i++) {
|
||||
if (line[i] === 1) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Key for memoization (primitive approach)
|
||||
// In a full solver, we'd pass a cache. For single line, maybe overkill, but safe.
|
||||
// let key = `${startIndex}-${hintIndex}`;
|
||||
// Skipping memo for now as line lengths are small (<80) and recursion depth is low.
|
||||
|
||||
const remainingLen = line.length - startIndex;
|
||||
// Min space needed: sum of hints + (hints.length - 1) spaces
|
||||
// Calculate lazily or precalc?
|
||||
let minSpace = 0;
|
||||
for(let i=hintIndex; i<hints.length; i++) minSpace += hints[i] + (i < hints.length - 1 ? 1 : 0);
|
||||
|
||||
if (remainingLen < minSpace) return false;
|
||||
|
||||
const block = hints[hintIndex];
|
||||
// Try to find *any* valid placement for this block
|
||||
// We only need ONE valid path to return true.
|
||||
for (let i = startIndex; i <= line.length - minSpace; i++) { // Optimization on upper bound?
|
||||
// Check placement
|
||||
let valid = true;
|
||||
// Block
|
||||
for (let k = 0; k < block; k++) {
|
||||
if (line[i+k] === 0) { valid = false; break; }
|
||||
}
|
||||
if (!valid) continue;
|
||||
|
||||
// Boundary before (checked by loop start usually, but strictly:
|
||||
if (i > 0 && line[i-1] === 1) valid = false; // Should have been handled by caller or skip
|
||||
// Wait, the caller (loop) iterates i.
|
||||
// If i > startIndex, we implied space at i-1.
|
||||
// If line[i-1] is 1, we can't place here if we skipped it.
|
||||
// Actually, if we skip a '1', that's invalid.
|
||||
// So we can't just skip '1's.
|
||||
|
||||
// Correct logic:
|
||||
// We iterate i. If we pass a '1' at index < i, that 1 is orphaned -> Invalid path.
|
||||
// So we can only scan forward as long as we don't skip a '1'.
|
||||
|
||||
let skippedOne = false;
|
||||
for (let x = startIndex; x < i; x++) {
|
||||
if (line[x] === 1) { skippedOne = true; break; }
|
||||
}
|
||||
if (skippedOne) break; // Cannot go further right, we left a 1 behind.
|
||||
|
||||
// Boundary after
|
||||
if (i + block < line.length && line[i+block] === 1) valid = false;
|
||||
|
||||
if (valid) {
|
||||
// Recurse
|
||||
if (canFitRest(line, i + block + 1, hints, hintIndex + 1)) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Solves the puzzle using logical iteration.
|
||||
* @param {number[][]} rowHints
|
||||
* @param {number[][]} colHints
|
||||
* @returns {object} { solvedGrid: number[][], percentSolved: number }
|
||||
*/
|
||||
export function solvePuzzle(rowHints, colHints) {
|
||||
const rows = rowHints.length;
|
||||
const cols = colHints.length;
|
||||
|
||||
// Initialize grid with -1
|
||||
let grid = Array(rows).fill(null).map(() => Array(cols).fill(-1));
|
||||
|
||||
let changed = true;
|
||||
let iterations = 0;
|
||||
const MAX_ITER = 100; // Safety break
|
||||
|
||||
while (changed && iterations < MAX_ITER) {
|
||||
changed = false;
|
||||
iterations++;
|
||||
|
||||
// Rows
|
||||
for (let r = 0; r < rows; r++) {
|
||||
const newLine = solveLine(grid[r], rowHints[r]);
|
||||
if (newLine) {
|
||||
for (let c = 0; c < cols; c++) {
|
||||
if (grid[r][c] !== newLine[c]) {
|
||||
grid[r][c] = newLine[c];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cols
|
||||
for (let c = 0; c < cols; c++) {
|
||||
const currentCol = grid.map(row => row[c]);
|
||||
const newCol = solveLine(currentCol, colHints[c]);
|
||||
if (newCol) {
|
||||
for (let r = 0; r < rows; r++) {
|
||||
if (grid[r][c] !== newCol[r]) {
|
||||
grid[r][c] = newCol[r];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate solved %
|
||||
let solvedCount = 0;
|
||||
for (let r = 0; r < rows; r++) {
|
||||
for (let c = 0; c < cols; c++) {
|
||||
if (grid[r][c] !== -1) solvedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
solvedGrid: grid,
|
||||
percentSolved: (solvedCount / (rows * cols)) * 100
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user