Organizing felt tip pens optimizing the arrangement of items in a 2D grid by similarity of adjacent items, using JS updated
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Arranging felt tip pens in a grid so adjacent pens are visually similar is a practical optimization problem. It appears simple, but the number of possible layouts grows quickly as pen count increases. A good solution balances quality and runtime by combining a clear similarity metric with a heuristic search algorithm.
Model The Problem
Represent each pen as a feature vector, usually RGB values from its color. Define a grid with fixed rows and columns, then define a score that rewards similar neighbors.
One common objective is minimizing total neighbor distance.
Lower score means better local color continuity.
Start With A Fast Baseline
A simple baseline is sorting by hue and filling the grid row by row. This is not optimal, but it gives a strong starting point for local optimization.
Good baselines reduce search time later.
Improve With Simulated Annealing
Because exact optimization is expensive, simulated annealing is a practical heuristic. Randomly swap two pens, accept better swaps always, and sometimes accept worse swaps early to escape local minima.
This approach performs well for medium grid sizes in browser or Node environments.
Practical UX Additions
If the goal is physical organization, exact global optimum may not be necessary. Users often prefer visually smooth gradients and grouped color families. Add domain constraints such as keeping brand groups together or reserving edge slots for special pens.
For interactive tools, show score improvements live and let users lock favorite positions before rerunning optimization.
Performance Considerations
For larger collections, recomputing full grid score after every swap can be costly. Optimize by recalculating only affected neighbor edges. This local delta update significantly reduces runtime.
Parallel search with multiple random seeds also helps. Run several annealing attempts and keep the best layout.
Common Pitfalls
- Using a similarity metric that does not match human color perception.
- Starting search from random layout only and wasting iterations.
- Recomputing full score for each swap in large grids.
- Treating one run as final without multi seed comparison.
- Ignoring practical constraints such as fixed positions or categories.
Summary
- Model pen arrangement as minimizing neighbor color distance in a grid.
- Build a baseline layout first, then optimize with heuristics.
- Simulated annealing is a practical method for large search spaces.
- Improve performance with local score updates and multi seed runs.
- Include user constraints for solutions that are both optimal and usable.

