From 4b80f3eedd61f8ad3d6a6f0acc7cd7168f44dc90 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Tue, 9 May 2023 13:25:19 -0500 Subject: [PATCH] Add a `joined` method with prefix/suffix Joining with a prefix and suffix is a relatively common operation that isn't terribly simple to implement concisely. This adds that operation for joining strings. Related to #195. --- Sources/Algorithms/Joined.swift | 10 ++++ Tests/SwiftAlgorithmsTests/JoinedTests.swift | 49 ++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/Sources/Algorithms/Joined.swift b/Sources/Algorithms/Joined.swift index 13f2f69b..9d721930 100644 --- a/Sources/Algorithms/Joined.swift +++ b/Sources/Algorithms/Joined.swift @@ -487,3 +487,13 @@ extension LazySequenceProtocol where Elements: Collection, Element: Collection { JoinedByClosureCollection(base: elements, separator: separator) } } + +extension Sequence where Element: Collection, Element.SubSequence == Substring { + public func joined(separator: Element, prefix: Element, suffix: Element) -> String { + var result = "" + result.append(contentsOf: prefix[...]) + result.append(contentsOf: self.joined(separator: separator[...])) + result.append(contentsOf: suffix[...]) + return result + } +} diff --git a/Tests/SwiftAlgorithmsTests/JoinedTests.swift b/Tests/SwiftAlgorithmsTests/JoinedTests.swift index 690659e5..6a341121 100644 --- a/Tests/SwiftAlgorithmsTests/JoinedTests.swift +++ b/Tests/SwiftAlgorithmsTests/JoinedTests.swift @@ -129,4 +129,53 @@ final class JoinedTests: XCTestCase { validator2.validate(strings.lazy.joined(by: { _, _ in separator })) } } + + func testJoinedPrefixSuffix() { + let input = [ + [5,3,0, 0,7,0, 0,0,0], + [6,0,0, 1,9,5, 0,0,0], + [0,9,8, 0,0,0, 0,6,0], + + [8,0,0, 0,6,0, 0,0,3], + [4,0,0, 8,0,3, 0,0,1], + [7,0,0, 0,2,0, 0,0,6], + + [0,6,0, 0,0,0, 2,8,0], + [0,0,0, 4,1,9, 0,0,5], + [0,0,0, 0,8,0, 0,7,9], + ] + + func prettyString(_ sudoku: [[Int]]) -> String { + sudoku.chunks(ofCount: 3).map { (bigChunk: ArraySlice<[Int]>) -> String in + bigChunk.map { (row: [Int]) -> String in + row.chunks(ofCount: 3).map { (smallChunk: ArraySlice) -> String in + smallChunk.lazy.map(String.init).joined(separator: " ", prefix: " ", suffix: " ") + }.joined(separator: "|", prefix: "|", suffix: "|") + }.joined(separator: "\n") + }.joined( + separator: "\n+-------+-------+-------+\n", + prefix: "+-------+-------+-------+\n", + suffix: "\n+-------+-------+-------+") + } + + let output = prettyString(input) + XCTAssertEqual( + output, + """ + +-------+-------+-------+ + | 5 3 0 | 0 7 0 | 0 0 0 | + | 6 0 0 | 1 9 5 | 0 0 0 | + | 0 9 8 | 0 0 0 | 0 6 0 | + +-------+-------+-------+ + | 8 0 0 | 0 6 0 | 0 0 3 | + | 4 0 0 | 8 0 3 | 0 0 1 | + | 7 0 0 | 0 2 0 | 0 0 6 | + +-------+-------+-------+ + | 0 6 0 | 0 0 0 | 2 8 0 | + | 0 0 0 | 4 1 9 | 0 0 5 | + | 0 0 0 | 0 8 0 | 0 7 9 | + +-------+-------+-------+ + """ + ) + } }