From 51cfde8c003d3bb2cf3a1b1d65a583f93eb76947 Mon Sep 17 00:00:00 2001 From: Alejandro Santiago Date: Wed, 20 Mar 2024 15:57:04 +0000 Subject: [PATCH] feat(board_generator_playground): define toPrettyString (#104) * feat: define toPrettyString * refactor: removed trim * refactor: removed unused import --- .../lib/src/crossword.dart | 38 +++++++++++++++++++ .../test/src/crossword_test.dart | 18 +++++++++ 2 files changed, 56 insertions(+) diff --git a/packages/board_generator_playground/lib/src/crossword.dart b/packages/board_generator_playground/lib/src/crossword.dart index 4c1552283..39324028c 100644 --- a/packages/board_generator_playground/lib/src/crossword.dart +++ b/packages/board_generator_playground/lib/src/crossword.dart @@ -370,4 +370,42 @@ class Crossword { constraints: constraints, ); } + + /// A pretty string representation of the board. + /// + /// For example, a board with the words "ALBUS" and "BEHAN" would be: + /// + /// ```txt + /// ALBUS + /// --E-- + /// --H-- + /// --A-- + /// --N-- + /// ``` + String toPrettyString() { + final stringBuffer = StringBuffer(); + + final minX = + characterMap.keys.map((e) => e.x).reduce((a, b) => a < b ? a : b); + final maxX = + characterMap.keys.map((e) => e.x).reduce((a, b) => a > b ? a : b); + final minY = + characterMap.keys.map((e) => e.y).reduce((a, b) => a < b ? a : b); + final maxY = + characterMap.keys.map((e) => e.y).reduce((a, b) => a > b ? a : b); + + final width = maxX - minX + 1; + + for (var row = minY; row <= maxY; row++) { + final characters = List.generate(width, (column) { + final location = Location(x: column + minX, y: row); + final character = characterMap[location]?.character ?? '-'; + return character.toUpperCase(); + }); + + stringBuffer.writeln(characters.join()); + } + + return stringBuffer.toString(); + } } diff --git a/packages/board_generator_playground/test/src/crossword_test.dart b/packages/board_generator_playground/test/src/crossword_test.dart index fbb3ce5d2..828069e63 100644 --- a/packages/board_generator_playground/test/src/crossword_test.dart +++ b/packages/board_generator_playground/test/src/crossword_test.dart @@ -849,5 +849,23 @@ void main() { }); }); }); + + group('toPrettyString', () { + test('returns a pretty string for the crossword', () { + final board = Crossword1(); + + final prettyString = board.toPrettyString(); + expect( + prettyString, + equals( + 'ALBUS\n' + '--E--\n' + '--H--\n' + '--A--\n' + '--N--\n', + ), + ); + }); + }); }); }