跳到正文
DEV Community· Gemy Brooks·· 5 小時前AI 評分27

用 JavaScript 按顏色統計拼豆數量

Count Perler beads by color with JavaScript

AI 導讀

JavaScript 程式可把拼豆圖案的網格轉換成各顏色的拼豆數量。範例心形圖案需要 19 顆紅色拼豆和 8 顆淺粉紅色拼豆,合共 27 顆;程式亦會指出網格行寬不一致或符號未列入顏色表的錯誤。

正文

Gemy Brooks

A bead pattern tells you where each color goes. If you want to check your supplies before you start, you can turn that same grid into a bead count with a short JavaScript script.

Turn the pattern into rows

Write one string for each row. Use a single letter for each color and a period for an empty peg. Keep the periods at the beginning and end of a row so every row has the same width. In the heart below, R is red and P is light pink.

const grid = [
  ".RR.RR.",
  "RRRPRRR",
  "RRPPPRR",
  ".RPPPR.",
  "..RPR..",
  "...R...",
];

const palette = new Map([
  ["R", "Red"],
  ["P", "Light pink"],
]);

function countBeads(grid, palette) {
  const width = grid[0]?.length ?? 0;
  const counts = new Map();

  for (const [rowIndex, row] of grid.entries()) {
    if (row.length !== width) {
      throw new Error(`Row ${rowIndex + 1} has ${row.length} cells. Expected ${width}.`);
    }

    for (const [columnIndex, symbol] of [...row].entries()) {
      if (symbol === ".") continue;

      const color = palette.get(symbol);
      if (color === undefined) {
        throw new Error(`Unknown symbol "${symbol}" at row ${rowIndex + 1}, column ${columnIndex + 1}.`);
      }

      counts.set(color, (counts.get(color) ?? 0) + 1);
    }
  }

  return [...counts].map(([color, beads]) => ({ color, beads }));
}

console.table(countBeads(grid, palette));

Check the count

Run the snippet in a browser console or save it as count-beads.js and run node count-beads.js. The heart needs 19 red beads and 8 light pink beads, for 27 beads total.

The script reports the row if you miss a cell while copying the grid. It reports the row and column if you use a symbol that’s missing from the palette. You can also assign two symbols to the same color name if you plan to use the same beads for both.

To try another grid, pick a small design from the perler bead patterns library on BeadSketch. Copy it row by row, update the palette, and compare the counts for a single row by hand before running the whole design.

This article was drafted with AI. The JavaScript example was run to verify the output.

來源:DEV Community · dev.to