Add tasks for all the new languages
This commit is contained in:
parent
9dc3c2bb62
commit
bba7bfd280
13208 changed files with 134745 additions and 0 deletions
14
Task/Run-length-encoding/Swift/run-length-encoding-1.swift
Normal file
14
Task/Run-length-encoding/Swift/run-length-encoding-1.swift
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import Foundation
|
||||
|
||||
// "WWWBWW" -> [(3, W), (1, B), (2, W)]
|
||||
func encode(input: String) -> [(Int, Character)] {
|
||||
return input.characters.reduce([(Int, Character)]()) {
|
||||
if $0.last?.1 == $1 { var r = $0; r[r.count - 1].0++; return r }
|
||||
return $0 + [(1, $1)]
|
||||
}
|
||||
}
|
||||
|
||||
// [(3, W), (1, B), (2, W)] -> "WWWBWW"
|
||||
func decode(encoded: [(Int, Character)]) -> String {
|
||||
return encoded.reduce("") { $0 + String(count: $1.0, repeatedValue: $1.1) }
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
|
||||
let output = decode(encode(input))
|
||||
print(output == input)
|
||||
15
Task/Run-length-encoding/Swift/run-length-encoding-3.swift
Normal file
15
Task/Run-length-encoding/Swift/run-length-encoding-3.swift
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
// "3W1B2W" -> "WWWBWW"
|
||||
func decode(encoded: String) -> String {
|
||||
let scanner = NSScanner(string: encoded)
|
||||
var char: NSString? = nil
|
||||
var count: Int = 0
|
||||
var out = ""
|
||||
|
||||
while scanner.scanInteger(&count) {
|
||||
while scanner.scanCharactersFromSet(NSCharacterSet.letterCharacterSet(), intoString: &char) {
|
||||
out += String(count: count, repeatedValue: Character(char as! String))
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
let encodedString = encode(input).reduce("") { $0 + "\($1.0)\($1.1)" }
|
||||
print(encodedString)
|
||||
let outputString = decode(encodedString)
|
||||
print(outputString == input)
|
||||
Loading…
Add table
Add a link
Reference in a new issue