Skip to content

Commit

Permalink
feat(board_generator_playground): define toPrettyString (#104)
Browse files Browse the repository at this point in the history
* feat: define toPrettyString

* refactor: removed trim

* refactor: removed unused import
  • Loading branch information
alestiago authored Mar 20, 2024
1 parent f9e8336 commit 51cfde8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
38 changes: 38 additions & 0 deletions packages/board_generator_playground/lib/src/crossword.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
18 changes: 18 additions & 0 deletions packages/board_generator_playground/test/src/crossword_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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',
),
);
});
});
});
}

0 comments on commit 51cfde8

Please sign in to comment.