KenKen Logic Puzzle
Overview
KenKen is a mathematical logic puzzle similar to Sudoku. Players fill a grid with numbers such that each row and column contains unique values, while groups of cells (cages) must satisfy arithmetic constraints. The element supports custom grid sizes and cage definitions.
Implementation Details
Puzzle Structure
The element receives a puzzle object containing:
size: Grid dimensions (e.g., 4 for a 4×4 grid)cages: Array of cage definitions with cells, target value, and operation
// Example element configuration
::: js KenKen
{
"size": 4,
"cages": [
{ "cells": [[0,0], [1,0]], "operation": "-", "target": 2 },
{ "cells": [[0,1], [0,2], [0, 3]], "operation": "*", "target": 24 },
{ "cells": [[1,1], [1,2], [2,2]], "operation": "+", "target": 6 },
{ "cells": [[2,0], [3,0], [3,1]], "operation": "*", "target": 24 },
{ "cells": [[2,1]], "target": 4 },
{ "cells": [[3,2], [3,3]], "operation": "/", "target": 2 },
{ "cells": [[1,3], [2,3]], "operation": "-", "target": 3 }
]
}
kenken1
autoPlay, allowFullscreen, saveStates
:::
Cage Visualization
The element dynamically calculates border widths for each cell based on cage membership. Cells on cage boundaries get thick borders (3px), while internal cage edges get thin borders (1px). This creates visual groupings without requiring manual border styling.
Cage labels appear in the top-left corner of the first cell (determined by minimum row/column) and display the target value with the operation symbol.
Validation Logic
The element performs three types of validation:
- Range checking: Values must be between 1 and grid size
- Row/column uniqueness: No duplicates in any row or column
- Cage arithmetic: Completed cages must satisfy their operation
Visual feedback uses background colors (red for errors, green for valid entries) to help users identify mistakes.
Technical Considerations
The cellCage mapping tracks which cage each cell belongs to, enabling O(1) lookups when determining borders and validating constraints. The element uses Set data structures to efficiently detect duplicates in rows and columns.
For division and subtraction operations with two numbers, the element checks both orderings (a/b and b/a) since the order isn’t specified in the puzzle definition.